根据R中的列绘制堆叠的条形图

时间:2019-04-27 19:44:17

标签: r ggplot2 stacked-chart

假设我具有以下数据框:

x = c(10,11,12,13)
x1 = c(0.50,0.55,0.58,0.62)
df <- data.frame(debt= c(0,1,2,3), x = x, x1 = x1, x2 = x-x1)

如何绘制类似下图的图?

enter image description here

1 个答案:

答案 0 :(得分:1)

例如:

library(ggplot2)
df2 <- reshape2::melt(df, id.vars = c("debt","x"))

ggplot(df2, aes(x = debt)) +
  geom_col(aes(y = value, fill = factor(variable, levels = c("x2","x1"))), width = 0.5) +
  geom_line(aes(y = x, colour = "steelblue"), size = 3) +
  scale_fill_manual(values = c("x1" = "darkorange", "x2" = "grey50"), name = "") +
  scale_colour_identity(guide = "legend", name = "", labels = "x") +
  scale_y_continuous(name = "x", expand = c(0,0,0.2,0)) +
  theme_minimal()

enter image description here

相关问题