antonina
antonina

Reputation: 109

Make barplot with ggplot but doesnt show bars

I have a data set like this

df1 
Ch   V
A    x1
B    x1
C    x2
D    x3
E    x2
..

I want to plot with a barplot the number of times V has been shown (on the y axis) while the values of V are shown on the x axis I tried this

df2 <- table(df$V)
df2
V1    Freq
x1     3
x2     4
..

(numbers for Freq are random in this example) and received a table to plot and my code for plotting using ggplot2 is

ggplot(df2, aes(x=V1, y=Freq)) + 
  geom_bar(stat = 'identity') 

It doesn't show me the bars though they are simply not shown. I made sure the values from df are both numerica.

What's the problem? Thank you!

Upvotes: 0

Views: 1900

Answers (1)

Ben
Ben

Reputation: 30474

@antonina - here is an example based on your post - can you reproduce this plot?

library(ggplot2)

df1 <- data.frame(
  Ch = c("A", "B", "C", "D", "E"),
  V = c("x1", "x1", "x2", "x3", "x2")
)

ggplot(df1, aes(x=V)) + 
  geom_bar(stat = "count") 

(or)

ggplot(df1, aes(x=V)) + 
  geom_bar(aes(y = ..count..))

example ggplot

Edit: Based on your comment, it might make sense to manipulate your data prior to plotting (e.g., using aggregate or tidyverse package). However, if you want to quickly plot counts for x1, x2, and x3 in a single bar, as you requested, then subset your data and include a single string or number for x aesthetic, something like:

ggplot(df1[df1$V %in% c("x1", "x2", "x3"),], aes(x = "Single")) + 
  geom_bar(stat = "count")

Again, I'm a bit confused on what you are looking for. I hope that this is helpful.

Upvotes: 2

Related Questions