plot_data <- rbind(
data.frame(year = seq(2018,2027), value = seq(1000,10000,1000), type = 'Type A'),
data.frame(year = seq(2018,2027), value = seq(500,5000,500), type = 'Type B')
)
plot_labels <- data.frame(year = seq(2018,2027), label = seq(1500,15000,1500))
ggplot(plot_data, aes(x=as.character(year), y=value, fill=type)) +
geom_bar(width = .6, stat='identity') +
# geom_text(data = plot_labels, aes(x = year, y = text, label = label)) +
scale_x_discrete(name = '') +
scale_y_continuous(name = 'My Label\n') +
scale_fill_manual(name = '', values = c('red', 'blue')) +
theme(
plot.title = element_text(size = 10, hjust = .5),
panel.grid.major = element_line(colour = 'white', size = 1),
panel.grid.minor = element_line(colour = 'white'),
plot.background = element_rect(fill = 'white'),
panel.background = element_rect(fill = 'white'),
axis.text.x = element_text(colour = 'grey20', size = 7, angle = 45, hjust = 1),
axis.title.y = element_text(color = 'grey20', size = 9),
axis.text.y = element_text(colour = 'grey20', size = 7),
legend.position='bottom',
legend.key.size=unit(5,'mm'),
legend.text = element_text(size = 7))
此代码将生成堆积条形图。
我的目标是在同一y轴上用plot_labels$label
标记此图,并按堆积条进行缩放。
在绘图定义中取消注释以geom_text
开头的行会引发以下错误:
Error in eval(expr, envir, enclos) : object 'type' not found
plot_labels$label
值相当于plot_data$value
总结plot_data$year
。
非常感谢排除故障的帮助!
答案 0 :(得分:1)
一些问题:
1)fill
应放在geom_bar
中,否则将由后面的所有geom继承。
2)当您同时提供geom_col
和geom_bar
时,x
优于y
。
3)在geom_text
中,x
和y
需要与ggplot
中的类型相同。
ggplot(plot_data, aes(x=as.character(year), y=value)) +
geom_col(aes(fill=type), width = .6) +
geom_text(data = plot_labels, aes(x = as.character(year), y = label, label = label), vjust = 0) +
scale_x_discrete(name = '') +
scale_y_continuous(name = 'My Label\n') +
scale_fill_manual(name = '', values = c('red', 'blue')) +
theme(
plot.title = element_text(size = 10, hjust = .5),
panel.grid.major = element_line(colour = 'white', size = 1),
panel.grid.minor = element_line(colour = 'white'),
plot.background = element_rect(fill = 'white'),
panel.background = element_rect(fill = 'white'),
axis.text.x = element_text(colour = 'grey20', size = 7, angle = 45, hjust = 1),
axis.title.y = element_text(color = 'grey20', size = 9),
axis.text.y = element_text(colour = 'grey20', size = 7),
legend.position='bottom',
legend.key.size=unit(5,'mm'),
legend.text = element_text(size = 7))