我在R中使用ggplot2创建地图。过去,我已经能够成功使用scale_fill_gradient()函数来控制geom_point填充。但是,当我运行下面的代码(提供示例表)时,我仅获得所有黑点的映射。图例看起来正确,但是这些点永远不会改变颜色。我认为我想要的变量没有映射到填充美学,但是我不知道为什么。预先谢谢你!
(如果有关系,我正在使用tibble包定义表)
table = tibble(long = c(15.28, 15.29, 15.3, 15.31, 15.32), lat = c(-4.4, -4.39, -4.38, -4.37, -4.36), consumption = c(NA, 3, 54, 6, 8))
mapping = aes_string(x = 'long', y = 'lat', fill = 'consumption')
# define breaks, limits, colors
low = 'seashell'
high = 'tan3'
breaks = c(0, max(na.omit(table)[['consumption']]))
limits = breaks
# plot
p <- ggplot() +
# points
geom_point(mapping = mapping, data = table, alpha = 0.7, size = 4) +
# point colors
scale_fill_gradient(low = low, high = high, na.value = 'darkgrey', guide = 'colorbar', aesthetics = 'fill'
, breaks = breaks, limits = limits) +
# title
ggtitle('consumption') +
# title formatting
theme(plot.title = element_text(color = "red", size = 10, face = "bold", hjust=0),
legend.position="bottom",
legend.text=element_text(size=9),
legend.title=element_text(size=9)) +
# legend
guides(fill=guide_colorbar(title='consumption')) +
# get rid of axes, etc.
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()) +
xlab('') +
ylab('') +
# make legend correct
theme(legend.box = 'vertical') +
# add max/min corresponding to map
xlim(c(15.28, 15.38)) +
ylim(c(-4.41, -4.30))
答案 0 :(得分:1)
如评论中所述,您必须将填充更改为颜色。这是我的实现方式:
library(tidyverse)
table = tibble(long = c(15.28, 15.29, 15.3, 15.31, 15.32), lat = c(-4.4, -4.39, -4.38, -4.37, -4.36), consumption = c(NA, 3, 54, 6, 8))
##Changed here to color
mapping = aes_string(x = 'long', y = 'lat', color = 'consumption')
# define breaks, limits, colors
low = 'seashell'
high = 'tan3'
breaks = c(0, max(na.omit(table)[['consumption']]))
limits = breaks
# plot
ggplot() +
# points
geom_point(mapping = mapping,
data = table, alpha = 0.7, size = 4) +
# point colors
#Change here to aesthetics = color
scale_color_gradient(low = low, high = high, na.value = 'darkgrey', guide = 'colorbar', aesthetics = 'color'
, breaks = breaks, limits = limits) +
# title
ggtitle('consumption') +
# title formatting
theme(plot.title = element_text(color = "red", size = 10, face = "bold", hjust=0),
legend.position="bottom",
legend.text=element_text(size=9),
legend.title=element_text(size=9)) +
# legend
guides(fill=guide_colorbar(title='consumption')) +
# get rid of axes, etc.
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()) +
xlab('') +
ylab('') +
# make legend correct
theme(legend.box = 'vertical') +
# add max/min corresponding to map
xlim(c(15.28, 15.38)) +
ylim(c(-4.41, -4.30))