简体   繁体   English

ggplot堆积的条形图问题

[英]ggplot stacked bar chart issue

I have the following data 我有以下数据

library(ggplot2)

d <- data.frame(
        Type= c("t1", "t2", "t3", "t4"),
        value= c(14000, 2500, 145, 900))

I want to create a horizontal stacked bar chart. 我想创建一个水平堆积的条形图。 I have the following code: 我有以下代码:

 ggplot(data = d, aes(x=Type, fill=value) ) + geom_bar() 

However this doesn't give me what I want. 但是,这不能给我我想要的东西。 I just need one bar with the values stacked on top of one another. 我只需要一个条形图,其值彼此堆叠。 Any help would be really appreciated. 任何帮助将非常感激。

Thanks 谢谢

If you have several x axis values ("t1", "t2", etc) the bars will not be stacked. 如果您有多个x轴值(“ t1”,“ t2”等),则这些条形将不会堆叠。 They will be only if they share the same x value. 仅当它们共享相同的x值时,它们才会出现。 That is solved with the dplyr pipe, that creates a temporary variable X . 这可以通过dplyr管道解决,该管道创建了一个临时变量X

Thanks to AntoniosK's comment for calling my atention to the OP's request for a horizontal bar. 感谢AntoniosK的评论 ,呼吁我注意OP要求的单杠

library(ggplot2)
library(dplyr)


d %>%
  mutate(X = factor(1)) %>%
  ggplot(aes(x = X, y = value, fill = value) ) + 
    geom_bar(stat = "identity", width = 0.2) +
  coord_flip()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM