I am new in R and just started to learn ggplot. I am so confused by the syntax, I thought the "color" and "fill" arguments should always follow color names or RGB specifications. But I've seen many cases where "color" and "fill" in aes() were assigned with variables, see the below example.
ggplot(faithfuld, aes(waiting, eruptions)) +
geom_raster(aes(fill = density))
I couldn't find an explanation of such use in [R documentation][1]. What does it mean? coloring by factor/grouping? if fill and color are assigned with variables, where should colors be specified? in scale_colour_manual?
Besides, I noticed that if specifying colors and/or transparency in aes(), the specified colors or transparency won't realise. For instance, in the below code, alpha = 0.3 is not working, I can change the alpha to any value, and the transparency will always be 0.5 in plotting. Why is that?
Also, I noticed that if I deleted fill or alpha in the aex(), the following "scale_fill_manual" wouldn't work. So is it true that "scale_fill_manual" is dependent on the geom_xx()?
p <- ggplot(dfcc) + geom_ribbon(aes(x = yr, ymax = ciupper, ymin = cilower, fill = "", alpha = 0.3)) +
scale_fill_manual(values = "blue", labels = "CI95%")
Sorry for so many questions, I am just so confused, and any help will be appreciated!
[1]: https://search.r-project.org/CRAN/refmans/ggplot2/html/aes_colour_fill_alpha.html
You can convey information about your data by mapping the aesthetics
in your plot to the variables in your dataset.
Please read Chapter 3 of R for Data Science when you got some time, it may answer your question. As examples, please see and observe the differences among these 3 set of code and their outputs:
1. Use Red as color:
iris |>
ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(color = "red") +
theme_minimal() +
theme(panel.grid = element_blank())
You get:
2. Use Species as color:
iris |>
ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(color = Species)) +
theme_minimal() +
theme(panel.grid = element_blank())
You get:
3. Modify Species with the color of your choice:
iris |>
ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(color = Species)) +
theme_minimal() +
theme(panel.grid = element_blank()) +
scale_color_manual(values = c("red", "yellow", "purple"))
You get:
Hope this is helpful.
Related
I'm using ggplot2 for map plots in R. How do I add a legend entry for a layer without a scale, just for a uniform color:
geom_polygon(data = watercourses, fill = "#0055aa", alpha = .5)
I just want to have the item title "Watercourses" and a color block representing the correct fill color. How does this work? So far, I only figured out how I can include scales to the legend.
Thank you!
EDIT: Here's an example with the NC dataset.
Map without centroids in legend
library(sf)
library(ggplot2)
demo(nc)
nc_centroids <- st_centroid(nc)
ggplot(nc) +
geom_sf(aes(fill = BIR74)) +
scale_fill_gradient(low = "white", high = "red") +
geom_sf(data = nc_centroids, color = "blue") +
coord_sf()
Wrong usage of aes() for legend
ggplot(nc) +
geom_sf(aes(fill = BIR74)) +
scale_fill_gradient(low = "white", high = "red") +
geom_sf(data = nc_centroids, aes(color = "blue")) +
coord_sf()
Trying to add the centroids to the legend (based on the answer of r2evans, https://stackoverflow.com/a/75346358/4921339)
ggplot(nc) +
geom_sf(aes(fill = BIR74)) +
scale_fill_gradient(low = "white", high = "red") +
geom_sf(data = nc_centroids, aes(color = "County centroids")) +
scale_fill_manual(name = "Centroids", values = c("County centroids" = "blue"))
coord_sf()
Throws the following messages and an error:
Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.
Error: Continuous value supplied to discrete scale
In my original case I use sp package instead of sf, but the messages and error thrown in the end are the same.
I think I did not yet understand how things work here, unfortunately. Any helping hints are highly appreciated.
If you place your fill in an aes(.), it will create a legend. Since you want a specific color, I suggest also adding scale_fill_manual:
ggplot(mtcars[-(1:3),], aes(mpg, disp)) +
geom_point() +
# placeholder for your `geom_polygon`:
geom_point(data = mtcars[1:3,], aes(fill = "something"), alpha = 0.5) +
scale_fill_manual(name = "something else", values = c("something" = "#0055aa"))
Perhaps this to add your blue points:
ggplot(nc) +
geom_sf(aes(fill = BIR74)) +
scale_fill_gradient(low = "white", high = "red") +
geom_sf(data = transform(nc_centroids, col = "County centroids"), aes(colour = col)) +
coord_sf() +
scale_colour_manual(name = NULL, values = c("County centroids" = "blue"))
EDIT by #winnewoerp: Explanation of how it works, for those who have problems understanding it all (like me until now...):
Add an extra column to the data frame with a unique value to be used within the legend, this can be done e.g. using the transform() function like in the given example or like df$col <- "Column unique value" prior to ggplot().
The (sole?) advantage to using transform is that there is no need to alter the original data, which might affect other processes on it (outside of this image). One disadvantage to doing it this way is that one must hard-code the "Column unique value" in both the transform and the scale_colour_manual, below.
Use scale_colour_manual() to add the legend item (blue colour example):
scale_colour_manual(
name = "Legend title",
values = c("Column unique value" = "blue")
)
I had been trying to include a legend in my plot that shows the name of the months next to the line with its respective colour and shape but I can't figure it out.
I have tried using scale_color_hue() but I got two different legends
isop_temp <- ggplot(bio_all_data, aes(t_2m, isop)) +
geom_jitter(aes(shape = month, colour = month, fill = month)) +
geom_smooth(aes(group = month, colour = month), method='lm',
fullrange = T, se = F) +
theme_bw() +
ylim(0, 4.5) +
xlab('temperature °C')+
ylab('Isoprene[ppb]') +
theme(legend.position = "top") +
scale_color_hue(labels = c('February','March','April','May','June'))
And this is what I am getting. What am I missing?
Short answer: you need to add scale_shape() with the same labels.
The issue here is that you map one variable (month) to 3 aesthetics - color, shape and fill. That would give you one legend, but the addition of scale_color_hue() separates the mapping of color and shape.
To illustrate using a reproducible example - we will omit fill because only color is relevant to geom_point. This works as expected:
library(ggplot2)
iris %>%
ggplot(aes(Sepal.Length, Petal.Width)) +
geom_point(aes(color = Species, shape = Species))
Now we add scale_color_hue. We get a separate legend because the labels differ to the default labels used when we mapped to shape:
iris %>%
ggplot(aes(Sepal.Length, Petal.Width)) +
geom_point(aes(color = Species, shape = Species)) +
scale_color_hue(labels = LETTERS[1:3])
The simplest fix is to use the same labels in scale_shape. Alternatively you could dplyr::mutate() the data frame to add a column with month name and map to that instead.
iris %>%
ggplot(aes(Sepal.Length, Petal.Width)) +
geom_point(aes(color = Species, shape = Species)) +
scale_color_hue(labels = LETTERS[1:3]) +
scale_shape(labels = LETTERS[1:3])
I am actually trying to do a graph with ggplot2 but I'd like to add some options (colors, legend...).
Here is my code :
ggplot(FINAL, aes(x = as.factor(gender), y=overtreatment)) +
stat_summary(fun.y="mean", geom="bar") +
facet_grid(. ~ treatment) +
theme_grey() +
xlab("Treatment") +
ylab("OT") +
scale_fill_grey() +
theme(strip.background = element_rect(colour = "black", fill = "white"))
And here the actual output.
Could you please indicate me how to change the name of 1 and 2 (without changing in it the dataframe) and how to add colours to this ?
I tried this
ggplot(FINAL, aes(x = as.factor(gender), y=overtreatment, colour=Treatment))
But it applies the color only to the outline of the figure.
To change the color of the bars you need fill = Treatment.
To change the labels on the x axis you need scale_x_discrete(labels = your_labels). See here.
So your code will look like:
ggplot(FINAL, aes(x = as.factor(gender), y=overtreatment, fill= Treatment)) +
scale_x_discrete(labels = your_labels) +
...
I am trying to add a legend to the graph but it doesn't work.
Do you have any ideas ?
Here is my code :
ggplot(data =stats_201507_AF ) +
geom_histogram(aes(gross_ind),fill="dodgerblue3", show.legend =T,bins=25)+
geom_histogram(aes(net_ind),fill="springgreen4",show.legend = T,bins=25) +
geom_histogram(aes(tax_ind),fill="gold2",show.legend = T, bins=25) +
xlab("Indices")+
scale_colour_manual(values=c("dodgerblue3","springgreen4","gold2"))
I wanted a description for every histogram with a corresponding colour.
Thanks a lot in advance
If you don't want to reshape your data, just do this:
ggplot(iris) +
geom_histogram(aes(x = Sepal.Length, fill = "Sepal.Length"),
position = "identity", alpha = 0.5) +
geom_histogram(aes(x = Sepal.Width, fill = "Sepal.Width"),
position = "identity", alpha = 0.5) +
scale_fill_manual(values = c(Sepal.Length = "blue",
Sepal.Width = "red"))
The key is that you need to map something to fill inside aes. Of course, reshaping your data to long format (and actually having a column to map to fill as a result) is usually preferable.
I wrote this few lines in order to plot some boxplots, and everything works:
plotSerie <- ggplot(fileIn) +
geom_boxplot(aes(x=DOY_S1, y=S1_VV, alpha=0.5, fill="S1", group=paste(fileIn$DOY_S1, sep=""))) +
geom_boxplot(aes(x=DOY_RS2, y=RS2_VV, alpha=0.5, fill="RS2", group=paste(fileIn$DOY_RS2, sep=""))) +
scale_fill_manual(name="Sensor", values=c("S1"="brown", "RS2"="grey"))
but I would like to define the trasparency in scale_fill_manual.
In google I found this solution, but doesn't work
plotSerie <- ggplot(fileIn)+
geom_boxplot(aes(x=DOY_S1, y=S1_VV, fill="S1",group=paste(fileIn$DOY_S1, sep=""))) +
geom_boxplot(aes(x=DOY_RS2, y=RS2_VV, fill="RS2", group=paste(fileIn$DOY_RS2, sep=""))) +
scale_fill_manual(name="Sensor", values=alpha(c("S1"="brown", "RS2"="grey"), 0.5))+
can you help me?
Thank you very much
Specify alpha in the geom:
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
geom_boxplot(alpha = 0.5) +
scale_fill_manual(values = c(setosa = "blue",
versicolor = "green",
virginica = "red"))
The transparency is adopted for the legend automatically.
Of course, you can also map a variable to a transparency scale with aes.