[英]Plot two variables in bar plot side by side using ggplot2
I think I need to use melt function but I'm not sure how to do so? 我想我需要使用melt函数,但不确定如何使用? Sample data, code, and resulting graph below.
示例数据,代码和结果图如下。 Basically, the "cnt" column is made up of the "registered" plus the "casual" for each row.
基本上,“ cnt”列由每行的“已注册”加上“休闲”组成。 I want to display the total "registered" vs the total 'casual" per month, instead of overall total "cnt"
我想显示每月的总“已注册”与总的“休闲”,而不是总的总“ cnt”
#Bar Chart
bar <- ggplot(data=subset(bikesharedailydata, !is.na(mnth)), aes(x=mnth, y=cnt)) +
geom_bar(stat="identity", position="dodge") +
coord_flip() +
labs(title="My Bar Chart", subtitle = "Total Renters per Month", caption = "Caption", x = "Month", y = "Total Renters") +
mychartattributes
To "melt" your data use reshape2::melt
: 要“融化”您的数据,请使用
reshape2::melt
:
library(ggplot2)
library(reshape2)
# Subset your data
d <- subset(bikesharedailydata, !is.na(mnth))
# Select columns that you will plot
d <- d[, c("mnth", "registered", "casual")]
# Melt according to month
d <- melt(d, "mnth")
# Set fill by variable (registered or casual)
ggplot(d, aes(mnth, value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge") +
coord_flip() +
labs(title="My Bar Chart", subtitle = "Total Renters per Month",
caption = "Caption",
x = "Month", y = "Total Renters")
Use tidyr and dplyr: 使用tidyr和dplyr:
set.seed(1000)
library(dplyr)
library(tidyr)
library(ggplot2)
bikesharedailydata <- data.frame(month = month.abb, registered = rpois(n = 12, lambda = 2), casual =rpois(12, lambda = 1))
bikesharedailydata %>% gather(key="type", value = "count", -month) %>%
ggplot(aes(x=month, y=count, fill = type))+geom_bar(stat = "identity", position = "dodge")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.