R 和 ggplot:无法标记来自第二个数据框的堆积条形图

R and ggplot: Trouble Labeling Stacked Bar Chart From Second Data Frame

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$valueplot_data$year.

总结

非常感谢您帮助解决问题![​​=17=]

几个问题: 1) fill 应该放在geom_bar 中,否则它会被后面的所有geom 继承。 2) 如果同时提供 xygeom_col 优于 geom_bar。 3) 在 geom_textxy 中需要与 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))