[英]Need to plot two variables on Y-axis ggplot
I am trying to plot two different variables on the Y-axis vs one variable on the X-axis.我试图在 Y 轴上绘制两个不同的变量,而在 X 轴上绘制一个变量。 I am using ggplot geom_bar for the same.我正在使用 ggplot geom_bar 。 However, the results are not coming in the way what I wanted.然而,结果并没有像我想要的那样。 My data frame looks as below:我的数据框如下所示:
DAY_OF_WEEK CATEGORY_TOTAL OVERALL_TOTAL CAT_PERCENT OVERALL_PERCENT
1 FRIDAY 4893 30542 16 20
2 MONDAY 5198 31197 17 20
3 SATURDAY 133 1139 12 1
4 THURSDAY 4806 29641 16 19
5 TUESDAY 5184 31757 16 21
6 WEDNESDAY 4569 28090 16 18
ggplot(my_data_frame, aes(x=DAY_OF_WEEK,y=CATEGORY_TOTAL,fill=OVERALL_TOTAL)) +
geom_bar(stat="identity",position = "dodge")
I need DAY_OF_WEEK on the X-axis, and two bars next to each other for each day.我需要 X 轴上的 DAY_OF_WEEK,以及每天相邻的两个条形。 One bar corresponding to CATEGORY_TOTAL and the other one for OVERALL_TOTAL.一根对应 CATEGORY_TOTAL,另一根对应 OVERALL_TOTAL。 Similarly I want another plot for the percentages as well.同样,我也想要另一个百分比图。 However, with the above ggplot statement, I am only getting one bar ie CATEGORY_TOTAL.但是,使用上面的 ggplot 语句,我只得到一个栏,即 CATEGORY_TOTAL。
Please suggest on how to achieve what I needed.请建议如何实现我所需要的。
Thanks谢谢
Here is a start for you;这是你的开始; first we melt the data and then we plot.首先我们融化数据,然后我们绘图。
library(ggplot2)
library(reshape2)
#relevel days of the week as more logical
dat$DAY_OF_WEEK <- factor(dat$DAY_OF_WEEK, levels=c("MONDAY","TUESDAY","WEDNESDAY","THURSDAY",
"FRIDAY","SATURDAY","SUNDAY"))
#turn to long
m_dat <- melt(dat,id="DAY_OF_WEEK")
#create grouping variable
m_dat$group <- gsub(".+_","",m_dat$variable)
#plot based on selection
p1 <- ggplot(m_dat[m_dat$group=="TOTAL",],
aes(x=DAY_OF_WEEK,y=value,group=variable,fill=variable)) +
geom_bar(stat="identity",position="dodge")
p1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.