Stacked Bar Chart in R using ggplot2

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

I am trying to create a Stacked Bar Graph using ggplot2. Here is how my data looks like

Date          Full.Page.Ads Total.Pages 11/10/2015                3          24 12/10/2015               10          24 13/10/2015               15          24 

This is the code which I am trying to use to visualize the data

library("ggplot2") library("reshape2")  ns <- read.csv("NS.csv")  ggplot(data=ns, aes(x = Date, y = Total.Pages, fill=Full.Page.Ads)) + geom_bar(stat = "identity") 

But for some reason rather than making a proper stacked bar chart, it keeps making something like this http://imgur.com/rqxEzjF.jpg. Rather than this I would like to show the main bars as Total.Pages and inside those bars, Full.Page.Ads bar in different colours.

I am not sure what I am doing wrong out here.

This is a sample of what I am aspiring to make http://blog.visual.ly/wp-content/uploads/2012/08/StackedPercent.png

回答1:

You have to melt your data before plotting. You also need to compute the difference between Total.Pages and Full.Page.Ads if you want your graph to represent the proportion of Full.Page.Ads with respect to the total number of pages. Something like:

ns <- data.frame(Date = c("11/10/2015", "12/10/2015", "13/10/2015"),                Full.Page.Ads = c(3, 10, 15),                Total.Pages = c(24, 24, 24))  #    Date Full.Page.Ads Total.Pages # 1 11/10/2015             3          24 # 2 12/10/2015            10          24 # 3 13/10/2015            15          24   ns$not.Full.Page.Ads <- ns$Total.Pages - ns$Full.Page.Ads ns$Total.Pages <- NULL ns2 <-melt(ns)  #        Date          variable value #1 11/10/2015     Full.Page.Ads     3 #2 12/10/2015     Full.Page.Ads    10 #3 13/10/2015     Full.Page.Ads    15 #4 11/10/2015 not.Full.Page.Ads    21 #5 12/10/2015 not.Full.Page.Ads    14 #6 13/10/2015 not.Full.Page.Ads     9  ggplot(data = ns2, aes(x = Date, y = value, fill = variable)) + geom_bar(stat = "identity") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!