【问题标题】:R bar chart data in rows行中的 R 条形图数据
【发布时间】:2018-09-11 09:19:25
【问题描述】:

我正在尝试在 R 中使用以下数据制作图表:

sex ethnicity x2015 x2016 x2017
-------------------------------

male    dutch      112    117   116   
female  dutch      114    118   120
female  german     102    101   99
etc     

我想从每个数据行制作一个条形图...

感谢您的帮助!!

【问题讨论】:

标签: r bar-chart


【解决方案1】:

您可以通过stat = identityfacet_wrap 使用ggplot2 包。此外,您可以使用 reshape2 包中的 melt 函数来转换数据以方便在 ggplot2 中使用 - 从宽数据集格式到窄数据集格式。请看下面的代码:

library(ggplot2)
library(reshape2)

data <- structure(list(sex = structure(c(2L, 1L, 1L), .Label = c("female", 
"male"), class = "factor"), ethnicity = structure(c(1L, 1L, 2L
), .Label = c("dutch", "german"), class = "factor"), x2015 = c(112L, 
114L, 102L), x2016 = c(117L, 118L, 101L), x2017 = c(116L, 120L, 
99L)), class = "data.frame", row.names = c(NA, -3L))

df <- melt(data)

ggplot(df, aes(x = ethnicity, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  facet_wrap(~ sex)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多