r - 修复多个绘图中的 ggplot 填充比例

标签 r ggplot2

基于此question ,多年来我一直在尝试绘制彩色编码 map 。考虑以下最小示例:

library(ggplot2)
states <- map_data("state")
var <- data.frame(table(states$region))
var$x1 = runif(49, 5.0, 7.5)
var$x2 = 2+runif(49, 5.0, 7.5)
states$x1 <- var$x1[match(states$region,var$Var1)]
states$x2 <- var$x2[match(states$region,var$Var1)]

## first plot
map <- ggplot(states, aes(x=long, y=lat,fill=x1,group=group))+ geom_polygon()
map = map + scale_fill_gradient(low='white', high='grey20')
print(map)

## second plot
map <- ggplot(states, aes(x=long, y=lat,fill=x2,group=group))+ geom_polygon()
map = map + scale_fill_gradient(low='white', high='grey20')
print(map)

绘图有效,但比例会根据每个绘图进行调整。因此,跨图表比较颜色没有意义。我想在所有图形中都有一个固定的“颜色数字”比例(我知道这样做可能会丢失图形中的一些细节)。

最佳答案

scale_fill_gradient 添加限制:

map <- ggplot(states, aes(x=long, y=lat,fill=x1,group=group))+ geom_polygon()
map = map + scale_fill_gradient(low='white', high='grey20', limits=c(1, 10))
print(map)

map <- ggplot(states, aes(x=long, y=lat,fill=x2,group=group))+ geom_polygon()
map = map + scale_fill_gradient(low='white', high='grey20', limits=c(1, 10))
print(map)

关于r - 修复多个绘图中的 ggplot 填充比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56539558/

相关文章:

r - 指定标签和中断时,ggplot scale_fill_identity 图例丢失

r - xts::apply 错误: "Error in coredata.xts(x) : currently unsupported data type"

r - 不想显示 ggplot2 中小刻度的所有标签

r - 循环和检查连续记录的条件并在 R 中替换

r - 基于另一列 (R) 值的列的累积和

删除 gridExtra::tableGrob 中的行名

r - 在图像层中对不同的填充比例进行动画处理

r - 使用带有多个分隔符的 strsplit

r - 将ggplot2与名称中带有空格的列一起使用

r - 根据 R 中的二维密度图计算值的概率