2017-09-08 56 views
0
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)) 

這段代碼將產生一個堆積條形圖。R和ggplot:麻煩標記來自第二個數據框的堆積條形圖

我的目標是在相同的y軸上標記這個圖,標記爲plot_labels$label,比例尺與堆積條相同。

在取消了線的情節定義與geom_text開始引發以下錯誤:

Error in eval(expr, envir, enclos) : object 'type' not found

plot_labels$label值等同於plot_data$year總結plot_data$value

非常感謝幫助排除故障!

+1

你必須添加'inherit.aes = FALSE'在'geom_text()'線,否則它繼承'從()''中定義ggplot審美映射填充= type',&嘗試查找用於'plot_labels'中名爲「type」的列。 –

+0

另外,我認爲在'geom_text()'的審美映射中它應該是'y = label'而不是'y = text'? –

+0

'y = text'是你的錯誤和很好的補充。加入'inherit.aes = FALSE'工作!多麼膨脹的傢伙,謝謝! –

回答

1

的幾個問題: 1)fill應放置在geom_bar,由以下所有geoms否則將被繼承。 2)當您同時提供xy時,geom_col優於geom_bar。 3)in 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)) 
+0

甜蜜,謝謝你的回答和建議!真的被困在這個陰謀一段時間。 –