r - 如何增加 ggplot2 map 连续颜色填充的箱数

标签 r ggplot2

我在使用 ggplot2 在 R 中创建 map 方面相对较新,但我已经为这个问题苦苦挣扎了几天。我已经创建了我的绘图,但似乎无法增加用于将颜色映射到我的值的容器数量。

这是一个问题,因为 map 不能很好地显示数据的变化。我不确定我是否正确解决了这个问题。

这是我的代码:

region=c('alaska','alabama','arkansas','arizona','california','colorado','connecticut','florida','georgia','hawaii','iowa','idaho','illinois','indiana','kansas','kentucky','louisiana','massachusetts','maryland','maine','michigan','minnesota','missouri','mississippi','montana','north carolina','north dakota','nebraska','new hampshire','new jersey','new mexico','nevada','new york','ohio','oregon','pennsylvania','south carolina','south dakota','tennessee','texas','utah','virginia','vermont','washington','wisconsin','west virginia','oklahoma','wyoming')

sales=c(46,1240,471,2292,13427,1574,261,10036,826,1508,184,939,2356,1329,434,271,714,208,2027,21,950,500,1871,147,249,1204,69,175,369,1968,606,656,2369,2422,525,2902,1709,126,1563,12046,931,2271,46,2260,250,122,0,0)

state_data = as.data.frame(cbind(region,sales))

library(ggplot2)
library(maps)
all_states <- map_data("state")

D = merge(all_states, state_data, by = "region")
D = D[with(D,order(D$group,D$order)),] 

p = ggplot()
p = p + geom_polygon( data=D, aes(x=long, y=lat, group = group, fill=D$sales),colour="white" )
p = p + xlab("")
p = p + ylab("")
p = p + labs(title = "sales")
p = p + guides(color=FALSE) 
p = p + guides(size=FALSE) 
p = p + guides(fill=guide_legend() )
p = p + guides(fill= guide_colorbar(title="sales",barheight = 1,barwidth=15,direction="horizontal",nbin=8) )
p = p + theme(legend.position="bottom")
p

理想情况下,我希望将图例上的 bin 数量增加到大约 8-10 个,并可能向渐变添加另一种颜色以显示更多细节。我尝试过 ggplot2 函数,但运气不佳。

最佳答案

您遇到的问题与您的 sales 列是一个因素而不是数字有关。以下方法可以解决这个问题:

D = merge(all_states, state_data, by = "region")
D = D[with(D,order(D$group,D$order)),] 
D$sales= as.numeric(D$sales) # this is the important bit...

p = ggplot(data=D) + 
     geom_polygon(aes(x=long, y=lat, 
                      group = group, fill=sales), 
                  colour = "white" ) + # Do not use D$, by use the column name
     xlab("") + ylab("") + labs(title = "sales") + theme(legend.position="bottom")
p

enter image description here

...或使用两种色标:

p + scale_fill_gradient2(midpoint = 20)

enter image description here

一些样式注释:

  • 请勿出于美观目的使用矢量 (D$sales),仅使用列名称 (sales)。
  • 我不喜欢常量 p = p + ... 样式,只需在行末尾使用 + 即可转到下一行。

关于r - 如何增加 ggplot2 map 连续颜色填充的箱数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901489/

相关文章:

r - 在 geom_histogram 中指定精确的 bin 范围

ggplot geom_area的R堆叠区域顺序

r - 更改 ggplot2 中条形图的绘制顺序

r - ggplot2 参数如何工作?

r - 在 geom_smooth 阈值之外的 ggplot 中标记值

r - 在 R 中使用 prop.table 循环变量

r - 通过指定要排除的行来应用 tidyr 以仅分隔特定行

r - 没有名为 'BiocInstaller' 的包

r - 使用带有嵌套列表的映射

r - 使用 group_rows 与 kableExtra 进行列对齐