ggplot2 palette legend does not show - r

I just started using ggplot2 R package and the following question should be very trivial, however I spent 2h on it without success.
I just need to show the scale_fill_distiller legend of the RdBu palette from -1 to 1 (red to blue) on my ggplot.
Here's a code example:
## Load ggplot2 package
require(ggplot2)
## Create data.frame for 4 countries
shape = map_data("world") %>%
filter(region == "Germany" | region == 'Italy' | region == 'France' | region == 'UK')
## Order data.frame by country name
shape = shape[with(shape, order(region)), ]
rownames(shape) = NULL # remove rownames
##### Assign 4 different values (between -1 and 1) to each country by creating a new column 'id'
## These will be the values to be plotted with ggplot2 palette
shape[c(1:605),'id'] = 0.2
shape[c(606:1173),'id'] = -0.4
shape[c(1174:1774),'id'] = -0.9
shape[c(1775:2764),'id'] = 0.7
##### Make plot
ggplot() +
## plot countries borders
geom_polygon(data = shape, aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
## adjust coordinates
coord_map() +
## remove any background
ggthemes::theme_map() +
## add colour palette
scale_fill_distiller(palette = 'RdBu', limits = c(1, -1), breaks = 50)
The legend of the RdBu palette should pop out automatically but here it doesn't. Is there any layer that is masking it?
OR
Is there any way to create a new legend from scratch and add it to the above plot?
I need something like the picture below, but from -1 to 1 (Red to Blue) and vertical:
Thanks

The range specified in limits should be c(min, max) and not c(max, min):
this works as expected:
library(ggmap)
library(ggplot2)
library(ggthemes)
ggplot() +
geom_polygon(data = shape,
aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
coord_map() +
ggthemes::theme_map() +
scale_fill_distiller(palette = 'RdBu', limits = c(-1,1))
while limits = c(1, -1) produces a plot without a colorbar:
ggplot() +
geom_polygon(data = shape,
aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
coord_map() +
ggthemes::theme_map() +
scale_fill_distiller(palette = 'RdBu', limits = c(1, -1))
If you would like to map the values in reverse order, you can use the direction argument:
ggplot() +
geom_polygon(data = shape,
aes(x = long, y = lat, group = group, fill = id), colour = 'black') +
coord_map() +
ggthemes::theme_map() +
scale_fill_distiller(palette = "RdBu",
limits = c(-1, 1),
breaks = c(-1, 0, 1),
direction = 1)

Related

overlay 2 point graphs on box plot in R

I'm having some issue overlaying 2 point graphs on a box plot. The code seems to work well when i added only one point graph. Here is the code below:
ggplot(data1, aes(x= reorder(DMU,order), y = Efficiency)) +
geom_boxplot() +
geom_point(data = data2, aes(x = dmu, y = eff, color = "eff")) +
scale_color_manual("", breaks = c("eff"), values = c("blue")) +
geom_point(data = data3, aes(x = DMU, y = eff2, color = "eff2")) +
scale_color_manual("", breaks = c("eff2"), values = c("red"))
I keep getting the error below:
Scale for 'colour' is already present. Adding another scale for
'colour', which will replace the existing scale.
Error: Insufficient values in manual scale. 2 needed but only 1 provided.
You cannot add scale_color_manual() twice.
Build a single dataframe for the colon:
df_points <- data.frame(x = c(data2$dmu, data3$DMU),
y = c(data2$eff, data3$eff2),
data = c("data2", "data3")
)
And then:
ggplot(data1, aes(x = reorder(DMU,order), y = Efficiency)) +
geom_boxplot() +
geom_point(data = df_points, aes(x = x, y = y, color = data)) +
scale_colour_manual(values = c("red", "blue") +
theme(legend.position = "none")
Not having the data available I could have made a mistake

How to add line to point shapes in ggplot2 legend

I want to create a black and white plot using ggplot2, where the data is plotted by category using a combination of lines and points. However, the legend only shows the point shape, with no line running through it, unless I add color to the plot.
Here is some example data to illustrate the problem with:
## Create example data
set.seed(123)
dat <- data.frame(
time_period = rep(1:4, each = 3),
category = rep(LETTERS[1:3], 4),
y = rnorm(12)
)
Here is an example of a color plot, so you can see how I want the legend to look:
library(ggplot2)
## Generate plot with color
ggplot(data = dat, mapping = aes(x = time_period, y = y, color = category)) +
geom_line(aes(group = category)) +
geom_point(aes(shape = category), size = 2) +
theme_bw()
However, if I move to grayscale (which I need to be able to do), the line running through the point in the legend disappears, which I'd like to avoid:
## Generate plot without color
ggplot(data = dat, mapping = aes(x = time_period, y = y)) +
geom_line(aes(group = category)) +
geom_point(aes(shape = category), size = 2) +
theme_bw()
How can I add a line through the point symbols in the legend with a grayscale plot?
I would suggest this approach:
#Plot
ggplot(data = dat, mapping = aes(x = time_period, y = y,group = category,shape = category)) +
geom_line(color='gray',show.legend = T) +
geom_point(size = 2) +
theme_bw()
Output:

distill colors of polygons on a map with ggplot2

I'm trying to plot the different ways to name a pencil in France on a map with ggplot2. For each of the 96 departments of France, I have one item and a score associated to this item. I have no problem plotting the items according to their departments on a map, but I can't figure out a way to make the colors of each polygons vary according to their associated score. My data is here. The code to produce the map is below:
library(ggplot2)
library(scales)
library(Cairo)
#open data
plotDatafr = read.table("plotDatafr.txt", header=T, sep="\t", quote="", dec=".")
g <- ggplot() +
geom_polygon(data = plotDatafr, aes(x=long, y = lat, group = group, fill=item), alpha=0.8, colour = "black") +
scale_fill_manual(values = c("#009E73", "#F0E442", "#0072B2", "#D55E00"), na.value=NA) +
theme_nothing(legend = TRUE) +
coord_map() #avoid distorsion
ggsave(g, filename = "crayon_euro.png", scale=1) #save for futher use
I tried to use the "scale_fill_distiller" command, but with such command I can only plot the properties of a single item, and I loose their given colors, for example:
g <- ggplot() +
geom_polygon(data = plotDatafr, aes(x = long, y = lat, group = group, fill = score), colour = "black", alpha = 0.8) +
scale_fill_distiller(palette = "Purples", breaks = pretty_breaks(n = 9), labels = percent, direction = 1, "", guide=FALSE) +
guides(fill = guide_legend(reverse = TRUE, override.aes = list(alpha = 1))) +
theme_nothing(legend = TRUE) +
coord_map() #avoid distorsion
ggsave(g, filename = "crayon_euro.png", scale=1) #save for futher use
Does anyone have any idea how I can make the different my polygons shades varying according to their numerical value? I can't figure a way to combine scale_fill_distiller and scale_fill_manual in the same time.
you could use scale_fill_gradient instead to adjust aes(fill) by plotDatafr$score:
#open plotting data
plotDatafr = read.table("plotDatafr.txt", header=T, sep="\t", quote="", dec=".")
# make mapping data object
fr <- map_data("france")
# plot
ggplot(fr, aes(x=long, y = lat, group = group)) +
geom_polygon(data = plotDatafr, aes(fill=score), alpha=0.8, colour = "black") +
scale_fill_gradient(low = "yellow", high = "blue", na.value=NA) +
coord_map()
scale_fill_distiller is designed for discrete data, so you would have to bin plotDatafr$score in some way, before using it.
The answer given by #Haboryme above works perfectly! The trick is to set the alpha with "score" directly in the aes() of geom_polygon, that is to say:
ggplot() + geom_polygon(data = plotDatafr, aes(x = long, y = lat, group = group, fill = item, alpha = score), colour = NA) + scale_fill_manual(values = c("#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"), name = "", na.value=NA) + coord_map()

Reverse color palette with legend limits ggplot2

I have a set of polygons, an reproducable example here from code in this question:
# polygons
square <- t(replicate(8, {
o <- runif(2)
c(o, o + c(0, 0.1), o + 0.1, o + c(0.1, 0), o)
}))
ID <- paste0('sq', seq_len(nrow(square)))
# Create SP
polys <- SpatialPolygons(mapply(function(poly, id) {
xy <- matrix(poly, ncol=2, byrow=TRUE)
Polygons(list(Polygon(xy)), ID=id)
}, split(square, row(square)), ID))
# Create SPDF and add a column for values
polys.df <- SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID))
polys.df#data$number <- c(1,2,3,4,5,6,7,8)
I then want to plot these with a single color palette, but want the highest numbers to be dark rather than light as in the default. After fortifying to use ggplot
f.polys = fortify(polys.df, region='id')
f.polys = merge(f.polys, polys.df#data, by.x='id', by.y='id')
I attempted to plot using a couple scale_fill_distiller options. So, this code works to set legend bar limits but doesn't reverse the palette:
ggplot() +
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') +
scale_fill_distiller(palette = "Oranges", limits = c(0,10), breaks=c(0,2,8))
And this code reverses the palette, without being able to assign limits and breaks:
ggplot() +
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') +
scale_fill_distiller(palette = "Oranges", trans = 'reverse')
When I try to combine the scale_fill_distiller arguments the palette does not reverse and I lose the scale bar. Any recommendations?
ggplot() +
geom_polygon(data = f.polys, aes(x = long, y = lat, fill=number, group = group), color = 'black') +
scale_fill_distiller(palette = "Oranges", trans = 'reverse',limits = c(0,10), breaks=c(0,2,8))
You need to switch your limits around so the range goes from high to low instead of low to high. This then matches the reversing of the scale and the legend gets drawn.
scale_fill_distiller(palette = "Oranges", trans = "reverse",
limits = c(10,0), breaks=c(0,2,8))

how to separate bubble plot legend by variable in ggplot2

I'm trying to build a bubble plot in ggplot2 that has two variables (Tmin and Tmax). The problem is that the legends are layered one on top of the other. I would like two separate legends. Also, I would like to adjust the bubble increment in the legend from 4 to 6 bubble sizes. Here's what I have thus far:
ggplot() + geom_path(data = westUS, aes(x = long, y = lat, group = group)) +
geom_point(data = myData, aes(x = long, y = lat, size = Tmin), pch = 1, color = "blue", stroke = 0.3) + scale_size_continuous(range = c(-2, 7.5)) + theme_bw() +
geom_point(data = myData, aes(x = long, y = lat, size = Tmax), pch = 1, color = "red", stroke = 0.3)
This is how the plot looks currently
Thanks!

Resources