我正在尝试做一个ggplot hack。我想通过一个变量(variable = Open.Burning)为我的条形图上色并'legendize‘,但条形图标签和堆栈周围的方框由另一个变量表示。我已经写下了大部分内容,但我仍然在努力根据变量Open.Burning来修改图例。
library(ggplot2)
library(scales)
library(grid)
muns = data.frame(cbind(
'Open.Burning'=c(0,0,0,0,1),
'Population.2010'=c(486,4130,843,2648,3950),
'Municipality'=c('Alert Bay', 'Mount Waddington RD-uninc', 'Port Alice', 'Port McNeill', 'Port Hardy'),
'Regional.District'=rep('Mount Waddington', 5),
'mp'=c(243.0, 2551.0, 5037.5, 6783.0, 10082.0),
'Open.Burning.Label'=c('Bylaw', 'No Bylaw', 'No Bylaw', 'No Bylaw', 'No Bylaw')), stringsAsFactors=FALSE)
muns$Population.2010 <- as.numeric(muns$Population.2010)
muns$mp <- as.numeric(muns$mp)
fp = factor(muns[,'Open.Burning'],
labels=c('white', 'lightblue1'),
levels=c(0,1))
fill.vals = as.character(fp)
names(fill.vals) = muns$Municipality
ggplot(muns, aes(x=Regional.District, y=Population.2010, fill=Municipality)) +
geom_bar(stat='identity', width=0.6, colour = "gray32") +
xlab('Open Burning') + ylab("Population 2010") +
scale_y_continuous(labels = comma) +
geom_text(aes(y = muns$mp, label=muns$Municipality), colour = "gray32", size = 3) +
scale_fill_manual(values=fill.vals, breaks=muns$Municipality, labels=muns$Open.Burning.Label) +
## to add a border the legend (but not on the chart)
guides(fill = guide_legend(reverse=TRUE, override.aes = list(colour = "black"))) +
theme(text=element_text(size=12),
axis.text.x = element_blank(),
legend.title=element_blank()
)我现在得到的是:

我想得到的是:

我真的不知道如何做到这一点。有什么想法吗?
谢谢!
发布于 2015-01-22 07:32:06
只需要用Open.Bylaw.Label填充并调整颜色因子。
library(ggplot2)
library(scales)
library(grid)
muns = data.frame(cbind(
'Open.Burning'=c(0,0,0,0,1),
'Population.2010'=c(486,4130,843,2648,3950),
'Municipality'=c('Alert Bay', 'Mount Waddington RD-uninc', 'Port Alice', 'Port McNeill', 'Port Hardy'),
'Regional.District'=rep('Mount Waddington', 5),
'mp'=c(243.0, 2551.0, 5037.5, 6783.0, 10082.0),
'Open.Burning.Label'=c('Bylaw', 'No Bylaw', 'No Bylaw', 'No Bylaw', 'No Bylaw')), stringsAsFactors=FALSE)
muns$Population.2010 <- as.numeric(muns$Population.2010)
muns$mp <- as.numeric(muns$mp)
fp = factor(muns[,'Open.Burning.Label'],
labels=c('white', 'lightblue1'),
levels=c('No Bylaw','Bylaw'))
fill.vals = as.character(fp)
names(fill.vals) = muns$Open.Burning.Label
ggplot(muns, aes(x=Regional.District, y=Population.2010, fill=Open.Burning.Label)) +
geom_bar(stat='identity', width=0.6, colour = "gray32") +
xlab('Open Burning') + ylab("Population 2010") +
scale_y_continuous(labels = comma) +
geom_text(aes(y = muns$mp, label=muns$Municipality), colour = "gray32", size = 3) +
scale_fill_manual(values=fill.vals, breaks=muns$Open.Burning.Label, labels=muns$Open.Burning.Label) +
## to add a border the legend (but not on the chart)
guides(fill = guide_legend(reverse=TRUE, override.aes = list(colour = "black"))) +
theme(text=element_text(size=12),
axis.text.x = element_blank(),
legend.title=element_blank()
)https://stackoverflow.com/questions/28078325
复制相似问题