HoHoHo
HoHoHo

Reputation: 311

geom_bar from ggplot to plot character variables of df length

I have a DF

a   b
A   1
B   1
C   1
B   1
B   1
A   1

I am trying to produce bar plot with ggplot with DF$a on x axis and DF$b on y axis. I use the following

p <- ggplot(DF, aes(a,b)) + geom_bar(stat="identity")

But it appears that ggplot plots only unique letters from DF$a while i want to plot all of those. How can i do it? Thank you for help.

Upvotes: 2

Views: 613

Answers (2)

joemienko
joemienko

Reputation: 2270

You could avoid defining a new variable as shown by @mhairi-mcneill by just pulling the rownames off as your x-value

ggplot(DF, aes(x = rownames(DF),y = b)) + 
  geom_bar(stat="identity") + 
  scale_x_discrete(labels = DF$a)

Upvotes: 2

Mhairi McNeill
Mhairi McNeill

Reputation: 1981

You could make a new variable called order, which is unique in each row and plot with that instead. Then you could relabel the x-axis to match the original variable.

df$order <- as.factor(1:nrow(df))

ggplot(df, aes(x = order, y = b)) +
  geom_bar(stat = 'identity') +
  scale_x_discrete(breaks = df$order, labels = df$a)

Upvotes: 3

Related Questions