繁体   English   中英

如何在R中创建分组条形图

[英]How to create grouped barchart in R

我想在R中创建分组的条形图。但是,当前使用的代码是创建堆叠的条形图。 我一周中的每一天都想要两个酒吧。 一个栏显示第一行数据,另一栏显示第二行数据。 有谁知道如何做到这一点?

#  Sample CSV data
x <- read.csv(text="month, mon, tues, wed, thurs, fri, sat, sun
  9, 1, 3, 5, 7, 1, 2, 2
  9, 1, 6, 8, 1, 1, 2, 3")


library(ggplot2)
# x <- read.csv("checkinlobby.csv")
y <- data.matrix(x)
barplot(y)

这是我的解决方案:

1st)创建一个新列,使我们可以将其传递给fill参数。

2)将数据从宽更改为长,以使ggplot更容易。

3rd)将日期变量设为一个因子并重新排序

4)使用位置=“道奇”进行绘图

library(tidyverse)

#  Sample CSV data
x <- read.csv(text="month, mon, tues, wed, thurs, fri, sat, sun
              9, 1, 3, 5, 7, 1, 2, 2
              9, 1, 6, 8, 1, 1, 2, 3")


##
graph <- x %>% mutate(rows = 1:nrow(x)) %>%
  gather(day, measure, -month, -rows) %>%
  mutate(day = factor(day,
  levels = c("mon","tues","wed","thurs", "fri", "sat","sun"))) %>%
  ggplot(aes(x = day, y = measure, fill = as.character(rows))) +
  geom_col(position = "dodge")

graph

暂无
暂无

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

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