简体   繁体   English

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

[英]How to create grouped barchart in R

I wanted to create a grouped bar chart in R. However, the code I am currently used is creating a stacked bar chart. 我想在R中创建分组的条形图。但是,当前使用的代码是创建堆叠的条形图。 I want two bars for each day of the week. 我一周中的每一天都想要两个酒吧。 One bar showing first row of data and another bar showing second row of data. 一个栏显示第一行数据,另一栏显示第二行数据。 Does anyone know how to do this? 有谁知道如何做到这一点?

#  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)

Here is my solution: 这是我的解决方案:

1st)Create a new column that will allow us to pass it to the fill argument. 1st)创建一个新列,使我们可以将其传递给fill参数。

2nd) Change the data from wide to long to make it easier for ggplot. 2)将数据从宽更改为长,以使ggplot更容易。

3rd) Make the day variable a factor and reorder it 3rd)将日期变量设为一个因子并重新排序

4th) Plot using position = "dodge" 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