简体   繁体   English

如何使用R控制水平堆积条形图中的值的范围

[英]How to control the range of values in horizontal Stacked Bar Plot using R

Following is the code which gives a stacked bar chart with Timeline values from 0-300. 以下代码给出了时间轴值为0-300的堆叠条形图。 But I want it to be from 1-24. 但我希望它是1-24。

R code: R代码:

library(ggplot2)
dataFrame <- data.frame(sr=c(1:72),
                      hours=c(1:24),
                      mode=factor(c(""),levels = c("SecureMessaging","WebLogs","IVR")),
                      status=factor(c("Inactive"),levels = c("Active","Inactive")))
dataFrame$mode[1:24] <- "SecureMessaging"
dataFrame$mode[25:48] <- "WebLogs"
dataFrame$mode[49:72] <- "IVR"
dataFrame$status[2] <- "Active"
dataFrame$status[7] <- "Active"
dataFrame$status[24] <- "Active"
dataFrame$status[2+24] <- "Active"
dataFrame$status[12+24] <- "Active"
dataFrame$status[15+24] <- "Active"
dataFrame$status[3+48] <- "Active"
dataFrame$status[5+48] <- "Active"
dataFrame <- na.omit(dataFrame)
plot <- ggplot(data=dataFrame, aes(x=mode, y=hours, fill=status)) + geom_bar(stat="identity")
plot <- plot+coord_flip()
plot <- plot+ggtitle("Data Analytics")
plot <- plot+xlab("Mode")
plot <- plot+ylab("Time Line")
print(plot)

在此处输入图片说明

Technically not a direct answer as I'm suggesting an alternate implementation using geom_tile : 从技术上讲不是直接的答案,因为我建议使用geom_tile的替代实现:

gg <- ggplot(data=dataFrame, aes(y=mode, x=factor(hours)))
gg <- gg + geom_tile(aes(fill=status))
gg <- gg + coord_equal()
gg <- gg + labs(x="Mode", y="Time Line", title="Data Analytics")
gg <- gg + theme_bw()
gg <- gg + theme(panel.grid=element_blank())
gg <- gg + theme(panel.border=element_blank())
gg <- gg + theme(legend.position="bottom")
gg

在此处输入图片说明

If you'd like to cut the result at 24 (in the range 0,300) then add before print(plot) the following line. 如果您想将结果剪切为24(在0,300范围内),则在print(plot)之前添加以下行。 The result is however not perfect yet, because the "inactive" bars stop before 24. 但是结果还不是很理想,因为“无效”条在24点之前停止。

plot <- plot+ylim(0,24)

However, I am not sure if you wanted this. 但是,我不确定您是否要这样做。 Probably you are not happy with the scaling from 0-300 that r applies and want to have it 0-24. 可能您不满意r适用于0-300的缩放比例,并希望将其设置为0-24。 In that case, try the following. 在这种情况下,请尝试以下操作。 "1" should replace "hours" in your plot function as indicated here: 如以下所示,“ 1”应替换绘图功能中的“小时”:

plot <- ggplot(data=dataFrame, aes(x=mode, 1, fill=status)) + geom_bar(stat="identity")

第二个选项的数字

Bar chart with proper x-axis: 带有正确x轴的条形图:

ggplot(dataFrame, aes(x=hours,y=status, fill=status))+ geom_bar(stat='identity')+ facet_grid(mode~.)

在此处输入图片说明

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

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