我刚刚开始使用ggplot2
R包,下面的问题应该很简单,但是我花了2小时没有成功。
我只需要在我的ggplot
上显示从-1到1(红到蓝)的RdBu
调色板的scale_fill_distiller
图例。
这是一个代码示例:
## 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)
RdBu
调色板的图例应该会自动弹出,但这里却没有。是否有任何层遮盖了它?
或者
有没有办法从头开始创建一个新的图例并将其添加到上面的图中?
我需要如下图所示的东西,但是从-1到1(红到蓝)和垂直:
谢谢
最佳答案
limits
中指定的范围应为 c(min, max)
而不是 c(max, min)
:
这按预期工作:
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)
生成不带颜色条的绘图:
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))
如果您想以相反的顺序映射值,可以使用direction
参数:
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)
关于r - ggplot2调色板图例不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304818/