Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

r - Horizontal Barplot in ggplot2

I was working on doing a horizontal dot plot (?) in ggplot2, and it got me thinking about trying to create a horizontal barplot. However, I am finding some limitations in being able to do this.

Here is my data:

df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"), 
                Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1))
df
str(df)

Initially, I generated a dot plot using the following code:

require(ggplot2)
ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_point(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") +
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) +
    opts(plot.title = theme_text(face = "bold", size=15)) +
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) +
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12))

However, I am now trying to create a horizontal barplot and finding that I am unable to do so. I've tried coord_flip() and that was not helpful either.

ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_bar(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") +
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) +
    opts(plot.title = theme_text(face = "bold", size=15)) +
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) +
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

Can anyone provide some assistance on how to generate a horizontal barplot in ggplot2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
ggplot(df, aes(x=reorder(Seller, Num), y=Avg_Cost)) +
  geom_bar(stat='identity') +
  coord_flip()

Without stat='identity' ggplot wants to aggregate your data into counts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...