I was trying to make a chart as the below in ggplot. I wanted the y labels to show the entire set of values from 1 to 50 but I only wanted to generate horizontal gridlines every 10 numbers. I thought adding minor_breaks and then controlling the theme would work. However, setting the major grid lines to element_blankseems to be overriding the minor gridlines as well. I found some questions here where people have asked about adding more gridlines than labels, but I want the reverse.
How can I set the number of gridlines to be smaller than the number of breaks? Thanks!
Here is the code for the plot:
library(nsRFA)
library(ggplot2)
library(dplyr)
data(hydroSIMN)
annualflows %>% ggplot(aes(x = anno, y = cod)) +
geom_point(
shape = 45,
size = 5,
col = "blue"
) +
scale_y_reverse(
breaks = 1:50,
labels = 1:50,
minor_breaks = seq(10, 50, by = 10)
) +
scale_x_continuous(breaks = seq(1920, 1980, by = 10)) +
labs(
x = "Year",
y = "Code"
) +
theme(
panel.background = element_blank(),
panel.border = element_rect(fill = NA),
text = element_text(size = 10),
panel.grid.major.x = element_line(color = "grey80"),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_line(color = "grey80") # This doesn't work
)
From reading this https://github.com/tidyverse/ggplot2/issues/403, it would appear that there are some issues surround minor_breaks. However, using geom_hline() should get you what you want.
library(nsRFA)
library(ggplot2)
library(dplyr)
data(hydroSIMN)
minors<-seq(10,50,by=10)
annualflows %>% ggplot(aes(x = anno, y = cod)) +
geom_point(
shape = 45,
size = 5,
col = "blue"
) +
scale_y_reverse(
breaks = 1:50,
labels = 1:50,
minor_breaks = seq(10, 50, by = 10)
) +
scale_x_continuous(breaks = seq(1920, 1980, by = 10)) +
labs(
x = "Year",
y = "Code"
) +
theme(
panel.background = element_blank(),
panel.border = element_rect(fill = NA),
text = element_text(size = 10),
panel.grid.major.x = element_line(color = "grey80"),
#panel.grid.major.y = element_blank(),
#panel.grid.minor.y = element_line(color = "grey80") # This doesn't work
)+
geom_hline(mapping=NULL, yintercept=minors,colour='grey80')
Related
I have a data with over 700 observations but below is a sample. Using geom_curve I want to make a plot where the line size(total_trips) corresponds to a color say 3 different colors. For instance between 0-100 (total_trips) can have a color of red
df <- data.frame(
origin_x = c(659627.8,642136.2,648774.7,659627.8,659627.8,658455.7,659627.8,659620.6,661641.8,656246.4),
origin_y = c(6473200,6473200,6462166,6473200,6473200,6467413,6473200,6467163,6479577,6487039),
dest_x = c(642136.2,659627.8,659627.8,648774.7,659620.6,659627.8,658455.7,659627.8,659627.8,659627.8),
dest_y = c(6456563,6473200,6473200,6462166,6467163,6473200,6467413,6473200,6473200,6473200
),
total_trips = c(4002,49878,2011,500,100,3000,2500,654,900,600))
I tried
ggplot() + geom_sf(data=shapefile, colour='grey', fill='grey93', size = 0.25) +
geom_curve(
data = df),
aes(
x = origin_x,
xend = dest_x,
y = origin_y,
yend = dest_y,
size = n,
colour= as.factor(c('red','blue'))),
curvature = 0.3
) + scale_alpha_continuous(range = c(0.09,1)) +
theme(
axis.title = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
plot.title = element_text(hjust = 0.5, size = 6),
plot.caption = element_text(hjust = 1),
plot.caption.position = 'plot',
axis.ticks = element_blank(),
panel.background = element_rect(fill = 'white'),
panel.grid = element_blank(),
plot.background = element_rect(color = NA, size = 0.5, fill=NA),
panel.border = element_rect(color = 'black', fill = NA, size=0.2) ,
legend.position = c(0.89,0.15),
legend.key.size = unit(0.4, 'cm'),
legend.text = element_text(size=7)
) +
annotation_scale(location = 'br', style = 'ticks') + coord_sf(crs=3301) +
annotation_north_arrow(location = 'tr', width = unit(0.20, 'cm'),height = unit(0.5,'cm'))
If I understand correctly - you want to change the colour of the line according to a categorised continuous variable (total_trips), we can do this:
Use cut to categorise the variable and give labels to the groups
Add this new variable to the aes(colour =.
library(dplyr)
library(ggplot2)
df <- df |> mutate(trips = cut(total_trips, c(0, 2000, 5000, 50000),
labels = c("0-2k", "2k-5k", "5k-50k")))
ggplot() +
geom_curve(data = df, aes(x = origin_x,
xend = dest_x,
y = origin_y,
yend = dest_y,
size = total_trips,
colour = trips
))
Output:
Not sure if this is what you want, though – your sample dataset doesn't contain the variable n that you mention in size = n, and you haven't provided us with shapefile.
I can't solve a problem I found when plotting and saving an image from raster with the ggsave() function in R.
When I plot it, it works well. When I use ggsave() to export it, horizontal gray lines are added to the plot.
I want to remove them but I don't know how to do it.
That's an example image with the options and the code I used:
gg.opzioni = list(geom_tile(aes(x, y, fill = values)),
scale_fill_gradientn(n.breaks = 3, colours = c("#52647A", "#2C413C", "#646859"), guide = "legend", na.value = "white"),
theme(plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12),
plot.margin = unit(c(2, 2, 2, 2), "mm"), panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.text.y = element_blank(),
axis.ticks.y = element_blank(), panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank(), aspect.ratio = 11/10),
scale_x_continuous(limits = c(0, 1), expand = c(0, 0), breaks = seq(0, 1, 0.1), labels = seq(0, 10, 1)),
scale_y_continuous(limits = c(0, 1), expand = c(0, 0), breaks = seq(0, 1, 0.1), labels = seq(0, 10, 1)),
coord_fixed())
r.sam = ggplot(df) + gg.opzioni + labs(title = "Campione ricostruito", x = "", y = "", fill = "classe:")
ggsave(filename = "lapalma_sam.png", plot = r.sam, device = "png", path = "/Users/Francesco/Downloads/")
I tried to remove the possible grid with the panel.grid options, but it didn't work.
Originally three variables are included in the df object: two of coordinates and one with the pixel class.
library(tidyverse)
df <- tibble(
val = rep(sin(seq(0, 4*pi, length = 100)), 100),
x = rep(1:100, 100),
y = rep(1:100, each = 100)
)
The following replicates your problem, where horizontal lines are visible around each cell:
plot.tiles <- ggplot(data = df, aes(x = x, y = y, fill = val)) +
geom_tile()
ggsave('plot_tile.png', plot.tiles)
This arises because geom_tile() has a border color property. One solution is to make the "color" aesthetic match the "fill" aesthetic:
plot.border <- ggplot(data = df, aes(x = x, y = y, fill = val, color = val)) +
geom_tile()
ggsave('plot_border.png', plot.border)
Or you can use geom_raster(), which does not have a cell border, but functions similarly to geom_tile():
plot.raster <- ggplot(data = df, aes(x = x, y = y, fill = val)) +
geom_raster()
ggsave('plot_raster.png', plot.raster)
I have plotted a line plot with confidence interval as below:
Here is the code I used:
Data_prob = read.table("group1.csv", header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)
p<-ggplot(Data_prob, aes(x=Trial, y=Data)) + theme_bw() + xlim(1, 49) + ylim(0.3, .95) +
theme(plot.title = element_text(color="black", size=14, face="bold.italic"), # plot title
axis.title.x = element_text(color="Black", size=25), # x label
axis.title.y = element_text(color="Black", size=25), # y label
axis.text.x = element_text(color = "black",face = "bold", # text style for x axis (removed face = "bold")
size = 22, angle = 0),
axis.text.y = element_text( color = "black",face = "bold", # text style for y axis
size = 22, angle = 0),
axis.line = element_line(color = "black", # line for x and y axis
size = 1, linetype = "solid"),
plot.caption = element_text(color = "black", size =11, face = "bold.italic"), # text style for caption
axis.ticks.length=unit(.25, "cm")
#axis.ticks = element_blank()
) +
theme(panel.border = element_blank(), # remove grid and background color
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
geom_ribbon(aes(ymin=Data-CI, ymax=Data+CI),
alpha=0.2, fill = "gold",color = "gray35", size = 0.1) +
geom_line(size=2, color="black")
print(p)
# Change axis labels
p <- p + labs(x = "Trial", y = "Go probability")
p
Here is what the data look like:
structure(list(Trial = 1:20, Data = c(0.500000027777778, 0.529220307827301,
0.519090892380421, 0.532167908861151, 0.598987738691911, 0.631452312399153,
0.669892859606973, 0.649994605133695, 0.675688232680895, 0.708304011267941,
0.720449809771278, 0.748081634160322, 0.761387966998141, 0.784275979741743,
0.786897508201414, 0.794196638795235, 0.785998558171792, 0.766138054176142,
0.790409435001615, 0.778745578955544), CI = c(5.44644605948509e-08,
0.073455696656296, 0.080875149623623, 0.073926617913334, 0.085753364225061,
0.068666346495005, 0.079656617789649, 0.077652237751934, 0.070180261163008,
0.071432599780653, 0.064943477844168, 0.064645277387821, 0.065096219183598,
0.065766579701286, 0.064325292909355, 0.066878706963396, 0.067698913200129,
0.07105300711211, 0.067063389995005, 0.069931673037628)), row.names = c(NA,
20L), class = "data.frame")
I would like to plot data from another group (group2.csv), so basically another line with confidence interval on the same graph to visually compare the two groups, ideally with a different line color. I've seen some examples on here but I couldn't get it to work. Could anyone help? Thank you!
Suppose you read your data up to two tibble from csv files.
library(tidyverse)
Data_prob1 =tibble(
Trial = 1:50,
Data = c(seq(0.5,0.8, length.out = 20), rep(0.8, 30))+rnorm(50,0,0.05),
CI = 0.1,
)
Data_prob2 =tibble(
Trial = 1:50,
Data = c(seq(0.8,1.2, length.out = 25), rep(1.2, 25))+rnorm(50,0,0.05),
CI = 0.08
)
You can combine such data like this
Data_prob = Data_prob1 %>% mutate(probe = "1") %>%
bind_rows(Data_prob2 %>% mutate(probe = "2")) %>%
mutate(probe = probe %>% fct_inorder())
Finally, create a chart
Data_prob %>% ggplot(aes(Trial, Data, fill=probe, color = probe))+
geom_line()+
geom_ribbon(aes(ymin=Data-CI, ymax=Data+CI, color=NULL), alpha=0.2)
This question already has answers here:
Wrap long axis labels via labeller=label_wrap in ggplot2
(4 answers)
Closed 2 years ago.
I know hjust is used for the x title axis, but how would I go about centering and multilining the x axis labels? Here is my plotting function:
gg_fun<-function(){
ggplot(tab,
aes(x = Var1, y = Percent)) +
#theme_light() +
theme(panel.background = element_rect(fill = NA),
axis.title.y=element_text(angle=0, vjust=0.5, face="bold"),
axis.title.x=element_blank(),
axis.text.y = element_text(size = 10),
axis.text.x = element_text(size = 12),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
#panel.grid.minor = element_line(colour = "dark gray"),
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line(size=.1, color="dark gray" ),
axis.line = element_line(size=.1, colour = "black"),
plot.background = element_rect(colour = "black",size = 1)) +
geom_bar(stat = "Identity", fill="#5596E6") + #"cornflower" blue
ggtitle(element_blank()) +
scale_y_continuous(expand = c(0, 0), breaks = round(seq(0, 1, by = .1), digits = 2),
labels = percent(round(seq(0, 1, by = .1), digits = 2), digits = 0),
limits = c(0,.6)) #+
#scale_x_discrete()
}
Here is an example graph it produces:
I am aware of n.dodge argument for scale_x_discrete(), but this is not what I am looking for. I also do not want to simply abbreviate using labels = abbreviate or specifying precisely as this is time consuming. I have also seen for example levels(birds$effect) <- gsub(" ", "\n", levels(birds$effect)), but this skips every line and makes some labels far too long. How would I go about centering the x label text as well as having it multiline to prevent overlap? Example of what I am going for:
You can use stringr::str_wrap as a labelling function in scale_x_discrete.
Let's take some sample data:
tab <- data.frame(Var1 = c("Video of presentation incl visuals",
"Video of presentation, written text and visuals",
"Written text, plus visuals",
"Other (please specify)"),
Percent = c(0.33, 0.34, 0.16, 0.17))
With your original function, this gives the following plot:
gg_fun()
But with the following modification:
gg_fun<-function(){
ggplot(tab,
aes(x = Var1, y = Percent)) +
#theme_light() +
theme(panel.background = element_rect(fill = NA),
axis.title.y=element_text(angle=0, vjust=0.5, face="bold"),
axis.title.x=element_blank(),
axis.text.y = element_text(size = 10),
axis.text.x = element_text(size = 12),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
#panel.grid.minor = element_line(colour = "dark gray"),
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line(size=.1, color="dark gray" ),
axis.line = element_line(size=.1, colour = "black"),
plot.background = element_rect(colour = "black",size = 1)) +
geom_bar(stat = "Identity", fill="#5596E6") + #"cornflower" blue
ggtitle(element_blank()) +
scale_y_continuous(expand = c(0, 0),
breaks = round(seq(0, 1, by = .1), digits = 2),
labels = scales::percent(round(seq(0, 1, by = .1),
digits = 2), digits = 0),
limits = c(0,.6)) +
scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 16))
}
We get:
gg_fun()
Typically, you have to manually place the newline character '\n' within your labels. However, someone wrote a function to do this automatically, which is provided in this thread.
I have the following bubble plot that shows the abundance percentage of microbes across different samples. However, I want to remove the tick labels called "Archaea" and "Other taxa" (located at either ends of the bubble plot) since the labels for both can be placed in the x-axis strip text instead. I used the following code to produce the plot:
ggplot(En.TaxMisc.NoC.RelAb.filtered.tidy$CombinedMisc,
aes(x = factor(Taxonomy, levels = En.TaxMisc.order$Taxonomy),
y = SampleSource, size = RelAb)) +
geom_point(colour = '#abd9e9') +
facet_grid(SampleType ~ Level,
labeller = labeller(SampleType = SampleType.NoC.labels),
scale = 'free', space = 'free') +
scale_x_discrete(name = NULL) +
scale_y_discrete(position = 'left', name = NULL) +
scale_size_continuous(name = str_wrap('Relative abundances (%)', width = 10),
breaks = c(1:8), range = c(0.75, 20)) +
guides(size = guide_legend(nrow = 1)) +
theme(legend.position = 'bottom',
legend.background = element_rect(colour = 'grey70'),
legend.title = element_text(size = 8, hjust = 1),
legend.text = element_text(size = 7, hjust = 0),
legend.spacing.x = unit(2.5, 'mm'),
legend.box = 'horizontal',
strip.background = element_rect(colour = 'grey55'),
strip.text.x = element_text(size = 8),
strip.text.y = element_text(size = 8),
axis.text.x.bottom = element_text(angle = 90, hjust = 1,
vjust = 0.3, size = 8),
axis.text.y.left = element_text(size = 8),
axis.ticks = element_blank(),
panel.grid.major.x = element_line(linetype = 1),
panel.border = element_rect(linetype = 1, fill = NA),
panel.background = element_blank())
I had tried to use scale_x_discrete(labels = c("Archaea" = NULL, "Other taxa" = NULL) but this resulted in all the tick labels being removed. I had also looked into using the rremove() function and the axis_ticks theme components, but neither appear to possess arguments for specifying tick labels.
I'd appreciate suggestions or advice anyone can give me!
There's a fair bit of extraneous detail in the question, but if you're just looking to remove (or customize!) tick labels, all you need is to add a labels argument to scale_x_discrete.
Self-contained example:
library(ggplot2)
ds = data.frame(
xVar = as.factor(rep(LETTERS[1:5],10)),
y = rnorm(50)
)
my_custom_labels = c("","level B","level C","level D!","")
ggplot(data = ds) +
geom_point(aes(x = xVar,y = y)) +
scale_x_discrete(labels = my_custom_labels)