我正在绘制美国地图,显示每个州的餐馆数量,但没有得到正确的图例。每个州的颜色取决于该州的餐馆范围。此代码完全可重现。
library(ggplot2)
windowsFonts(Arial=windowsFont("TT Arial"))
colorsnew <- c("#C6D7A9","#9DAED9","#C6D7A9","#4A77BB","#9DAED9","#9DAED9","#C7C6C5","#C7C6C5","#4A77BB","#7aad42","#C7C6C5",
"#4A77BB","#9DAED9","#C6D7A9","#C6D7A9","#C6D7A9","#C6D7A9","#C7C6C5","#9DAED9","#7aad42","#7aad42","#9DAED9","#C6D7A9","#9DAED9",
"#C7C6C5","#C7C6C5","#C6D7A9","#C7C6C5","#7aad42","#C7C6C5","#4A77BB","#7aad42","#C7C6C5","#7aad42","#C6D7A9","#9DAED9","#4A77BB",
"#C7C6C5","#9DAED9","#C7C6C5","#9DAED9","#4A77BB","#C6D7A9","#C7C6C5","#9DAED9","#9DAED9","#C7C6C5","#9DAED9","#C7C6C5")
color_legend <- c("0-5000", "5000-10000","10000-20000","20000-30000","30000+")
usa_map <- map_data("state")
plotObj <- ggplot(usa_map, aes(x=long,y=lat,group=group))
plotObj <- plotObj + geom_polygon(data=usa_map, aes(x=long,y=lat,group=group,fill=region), colour ="white")
plotObj <- plotObj + scale_fill_manual(values=as.character(colorsnew), label=color_legend)
plotObj <- plotObj + theme(axis.line=element_blank(),axis.text.x=element_blank(),
axis.text.y=element_blank(),axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.text = element_text(family = "Arial"), legend.position = "top",
legend.title = element_text(family = "Arial", size = rel(1)),
strip.text = element_text(family = "Arial"),
panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),plot.background=element_blank())
plotObj <- plotObj + labs(title="Distribution of Restaurants across states in U.S. and Canada")
print(plotObj)
我的问题是图例应该根据color_legend向量显示我可以标记的每种颜色。但是,当我设置legend.position = "top"
时,它会显示所有49个州的颜色。如何设置图例,使每种颜色只显示一次适当的标签?我尝试过使用geom_map,但它给了我奇怪的错误。谢谢!
答案 0 :(得分:0)
您可以手动设置填充颜色的标签:
plotObj <- plotObj + scale_fill_manual(
values=as.character(unique(colorsnew),
labels=color_legend
)
我无法在你的场景中测试它,所以我不确定它是否有效。我假设你还必须设置legend.position =“top”或者将这一点评论出来。
编辑: 您的图例仅显示前5个状态,因为您只为scale_fill_manual提供了5个标签。在你提供整个列map.df $ colors_new之前我错过了你的例子,我假设它是49个值,所以缺少44个值。
要解决此问题,请尝试在您的向量周围添加唯一值(请参见上文)。这会将列减少到5个单色值。请注意颜色的顺序是正确的。或者,您只需按正确的顺序构建一个包含5个颜色值的矢量。
colorsnew <- c("#C6D7A9","#9DAED9","#4A77BB","#C7C6C5","#7aad42")
我希望这次有效。