![](/img/trans.png)
[英]Is it possible to create single stacked column chart using plotly in R
[英]Create a stacked column chart in R
我正在嘗試使用 R 創建堆積柱形圖。
我有一個看起來像這樣的 dataframe:
數據df
:
structure(list(Period = c("1971-1989", "1990-1999", "2000-2009",
"2010-2019", "2020-2029"), Cold = c(-1.02, -0.3, -0.13, 0, 0.09
), Heat = c(6.08, -0.4, -0.1, 0, 0.17)), class = "data.frame", row.names = c(NA,
-5L))
期間為 chr,其他為 num。 我想制作一個看起來像這樣的堆積柱形圖:(我使用 Excel 制作的)
我嘗試使用ggplot
:
ggplot(df, aes(fill=cold, y=heat, x=Period)) +
geom_bar(position="stack", stat="identity")
但我無法像我想要的那樣得到堆疊的 plot。
任何幫助將非常感激。
首先將寬 data.frame 轉換為長格式,然后基本上使用您之前所做的:
df <- structure(list(Period = c("1971-1989", "1990-1999", "2000-2009",
"2010-2019", "2020-2029"), Cold = c(-1.02, -0.3, -0.13, 0, 0.09
), Heat = c(6.08, -0.4, -0.1, 0, 0.17)), class = "data.frame", row.names = c(NA,
-5L))
library(magrittr)
library(ggplot2)
library(reshape2)
df %>%
reshape2::melt() %>%
ggplot(aes(x=Period, y=value, fill=variable)) +
geom_bar(position="stack", stat="identity") +
guides(x = guide_axis(angle = 45)) # rotate x-axis label by 45°
從這里您現在可以根據需要修改軸和標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.