简体   繁体   中英

ggplot2 two level bar charts (aim with same size of bar)

I would like to plot two-level bar charts with following code,

with dataset

Date <- as.yearmon(rep(as.yearmon(c("Jun 2013", "Jun 2014"), format="%b %Y"), 4))[1:7]
Mktg.Al <- c("CX", "CX", "GA", "GA", "HX", "HX", "KA")
Seats <- sample(300:1000,7)
data <- data.frame(Date, Mktg.Al, Seats)

code for plotting

ggplot(data, aes(x=as.factor(Date), y=Seats, fill=Mktg.Al)) +   
geom_bar(position = "Dodge", stat="identity", size=10) +
geom_text(aes(label=Seats), position=position_dodge(width=0.9), vjust=-0.25)

在此处输入图片说明

I would like to have same size of each bars

Many thanks

Try mentioning all aesthetics at one place. this might work. i am not sure because you havent provided any sample data to check. use position="dodge" in geom text as well

ggplot(DATA.Yty.agg, aes(x = as.factor(Date),y = Seats,label=Seats,fill = Mktg.Al)) +   
geom_bar(position = "Dodge", stat="identity") +
geom_text(vjust=-0.2,position="dodge")

I solved the question by adding following graph after create the data.frame data

colnames <- colnames(data)
data <- as.data.frame(xtabs(formula = Seats ~ Date + Mktg.Al, data=data))
colnames(data) <- colnames

In total,

Date <- as.yearmon(rep(as.yearmon(c("Jun 2013", "Jun 2014"), format="%b %Y"), 4))[1:7]
Mktg.Al <- c("CX", "CX", "GA", "GA", "HX", "HX", "KA")
Seats <- sample(300:1000,7)
data <- data.frame(Date, Mktg.Al, Seats)
colnames <- colnames(data)
data <- as.data.frame(xtabs(formula = Seats ~ Date + Mktg.Al, data=data))
colnames(data) <- colnames

ggplot(data, aes(x=as.factor(Date), y=Seats, fill=Mktg.Al)) +   
geom_bar(position = "Dodge", stat="identity", size=10) +
geom_text(aes(label=Seats), position=position_dodge(width=0.9), vjust=-0.25)

Output graph would be 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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