Minfetli
Minfetli

Reputation: 299

Change the scale of x axis in ggplot

I have a ggplot bar and don't know how to change the scale of the x axis. At the moment it looks like on the image below. However I'd like to reorder the scale of the x axis so that 21% bar is higher than the 7% bar. How could I get the % to the axis? Thanks in advance!

enter image description here

df= data.frame("number" = c(7,21), "name" = c("x","y"))
df
ggplot(df, aes(x=name, y=number)) + 
  geom_bar(stat="identity", fill = "blue") + xlab("Title") + ylab("Title") + 
  ggtitle("Title") 

Upvotes: 0

Views: 2180

Answers (2)

Ron Sokoloff
Ron Sokoloff

Reputation: 130

The only way I am able to duplicate the original plot is, as @sconfluentus noted, for the 7% and 21% to be character strings. As an aside the data frame column names need not be quoted.

df= data.frame(number = c('7%','21%'), name = c("x","y"))
 df
 ggplot(df, aes(x=name, y=number)) + 
   geom_bar(stat="identity", fill = "blue") + xlab("Title") + ylab("Title") + 
   ggtitle("Title")

enter image description here

Changing the numbers to c(0.07, 0.21) and adding, as @Mohanasundaram noted, scale_y_continuous(labels = scales::percent) corrects the situation: enter image description here

To be pedantic using breaks = c(0.07, 0.21) creates nearly an exact duplicate. See also here.3 Hope this is helpful.

library(ggplot2)
library(scales)
df= data.frame(number = c(0.07,0.21), name = c("KG","MS"))
df
ggplot(df, aes(x=name, y=number)) + 
  geom_bar(stat="identity", fill = "blue") + xlab("Title") + ylab("Title") + 
  ggtitle("Title") + scale_y_continuous(labels = scales::percent,  breaks = c(.07, .21)))

enter image description here

Upvotes: 1

Mohanasundaram
Mohanasundaram

Reputation: 2949

Use the prop.table function to in y variable in the geom plot.

ggplot(df, aes(x=name, y=100*prop.table(number))) + 
  geom_bar(stat="identity", fill = "blue") + 
  xlab("Stichprobe") + ylab("Paketmenge absolut") + 
  ggtitle("Menge total")  

enter image description here

If you want to have the character, % in the y axis, you can add scale_y_continuous to the plot as below:

library(scales)

ggplot(df, aes(x=name, y=prop.table(number))) + 
  geom_bar(stat="identity", fill = "blue") + 
  xlab("Stichprobe") + ylab("Paketmenge absolut") + 
  ggtitle("Menge total") + 
  scale_y_continuous(labels=percent)

enter image description here

Upvotes: 2

Related Questions