簡體   English   中英

R中帶有ggplot2的堆疊Barplot

[英]Stacked Barplot in R with ggplot2

我有一個關於使用ggplot2在R中創建堆疊式barplot的問題。 我要創建的是一個堆積的條形圖,其中每個條形圖都放置在另一個條形圖的“頂部”。

x = c(100,200,400,600,800,1000,1250,1500)
y1 = c(1,2,3,4,5,6,7,8)
y2 = c(8,7,6,5,4,3,2,1)
data <- data.frame(x,y1,y2)
ggplot(data, aes(x, y1,label=x)) + 
  geom_bar(stat="identity", fill="blue", position="stack") +     
  geom_bar(stat="identity",aes(x, y2), fill="orange", position="stack")

我現在得到的是堆積的酒吧。 但是對於x = 100,我從0-1得到一個小節,從0-8中得到一個小節。但是我想要得到的是從0-1中得到一個小節,從1-9中得到一個小節。

您是否知道如何解決此問題(無需手動匯總輸入)?

謝謝你的幫助!

嘗試:

ggplot(melt(data, id='x')) + geom_bar(aes(x=x, y=value, fill=variable), stat='identity')

在此處輸入圖片說明

怎么樣:

df <- data.frame(x = c(x,x), y = c(y1, y2), grp = factor(rep(c("Grp 1", "Grp 2"), each = 8)))
ggplot(df, aes(x, y, fill = grp)) + geom_bar(stat = "identity", position="stack")

如果要調整顏色,請使用scale_fill_manual

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM