Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal Barplot in ggplot2

Tags:

r

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?

like image 356
ATMathew Avatar asked Jun 07 '12 23:06

ATMathew


People also ask

How do I change the width of a bar in ggplot2?

To Increase or Decrease width of Bars of BarPlot, we simply assign one more width parameter to geom_bar() function. We can give values from 0.00 to 1.00 as per our requirements.

What is horizontal bar graph?

A horizontal bar chart is a graph in the form of rectangular bars. It's a data visualization technique. The length of these bars is proportional to the values they represent. The bar chart title indicates which data is represented.


2 Answers

As off ggplot2 version 3.3.0 (March 2020) the direction is deducted from the aesthetic mapping. Hence we can simplify @Justin's and @ungatoverde code to

library(ggplot2) ggplot(df,        aes(x = Avg_Cost,            y = reorder(Seller, Num)            )        ) +   geom_col() 

enter image description here

Reference: https://www.tidyverse.org/blog/2020/03/ggplot2-3-3-0/#bi-directional-geoms-and-stats

like image 38
markus Avatar answered Sep 24 '22 17:09

markus


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.

like image 65
Justin Avatar answered Sep 21 '22 17:09

Justin