我刚刚开始使用ggplot2
R包,下面的问题应该非常简单,但我花了2小时就没有成功。
我只需要在scale_fill_distiller
上显示RdBu
调色板的ggplot
传奇,从-1到1(红色到蓝色)。
这是一个代码示例:
## 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
调色板的图例应自动弹出,但此处不会。是否有任何图层掩盖它?
OR
有没有办法从头开始创建新图例并将其添加到上图?
我需要类似下图的内容,但是从-1到1(红色到蓝色)和垂直:
由于
答案 0 :(得分:4)
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))
而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)