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

时间:2017-09-08 17:32:07

标签: r ggplot2 geom-bar geom-text

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

非常感谢排除故障的帮助!

1 个答案:

答案 0 :(得分:1)

一些问题: 1)fill应放在geom_bar中,否则将由后面的所有geom继承。 2)当您同时提供geom_colgeom_bar时,x优于y。 3)在geom_text中,xy需要与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))