【问题标题】:How to do a stacked bar chart with specific values for X axis in ggplot?如何在ggplot中制作具有X轴特定值的堆积条形图?
【发布时间】:2016-07-13 15:50:24
【问题描述】:

到目前为止,我一直在研究许多关于此的教程,但均未成功。 我有这个简单的数据集。

TestCases     Column-1  Column-2 
TestCase-1        2       5     
TestCase-2        3       8
TestCase-3        4       7
TestCase-4        5       9
TestCase-5        2       7

我需要在 ggplot 中制作一个堆叠直方图,结合 Column-1 和 Column-2 的值,并在 X 轴上包含 TestCases 列的名称,例如 TestCase-1、TestCase2 等。

【问题讨论】:

  • 也许您遇到的部分问题是您所描述的不是直方图,而是条形图。
  • 我认为您的意思是堆积条形图,因为您正在查看离散值。请参阅基础 R 中的 barplotggplot2 中的 geom_bar
  • 是的,确实是堆积条形图,我在 ggplot 中看到 geom_bar 但目前没有得到任何结果

标签: r ggplot2 histogram stacked-chart


【解决方案1】:

您需要先使用tidyr::gather 重塑数据,然后才能使用ggplot 进行绘图。

df <- read.table(header = TRUE, text = "
  TestCases     Column-1  Column-2 
  TestCase-1        2       5     
  TestCase-2        3       8
  TestCase-3        4       7
  TestCase-4        5       9
  TestCase-5        2       7")

df2 <- tidyr::gather(df, key = "Column", value = "Values", -TestCases)
ggplot(df2, aes(x = TestCases, y = Values, fill = Column)) +
  geom_bar(stat = "Identity")

【讨论】:

  • 我仍然想知道如何将我从 R 读取的 CSV 数据转换为包含数据的文本,正如您发布的那样。但是,它奏效了!!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2020-12-27
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多