Reputation: 1377
I have a data-frame 'x'
I tried
barplot(x$Value, names.arg = x$'Categorical variable')
ggplot(as.data.frame(x$Value), aes(x$'Categorical variable')
Nothing seems to work properly. In barplot, all axis labels (freq values) are different. ggplot is filling all bars to 100%.
Upvotes: 0
Views: 3173
Reputation: 168
You can try plotting using geom_bar(). Following code generates what you are looking for.
df = data.frame(X = c("A","B C","D"),Y = c(23,12,43))
ggplot(df,aes(x=X,y=Y)) + geom_bar(stat='identity') + coord_flip()
Upvotes: 2
Reputation: 3292
It helps to read the ggplot
documentation. ggplot
requires a few things, including data
and aes()
. You've got both of those statements there but you're not using them correctly.
library(ggplot2)
set.seed(256)
dat <-
data.frame(variable = c("a", "b", "c"),
value = rnorm(3, 10))
dat %>%
ggplot(aes(x = variable, y = value)) +
geom_bar(stat = "identity", fill = "blue") +
coord_flip()
Here, I'm piping my dat
to ggplot
as the data
argument and using the names of the x
and y
variables rather than passing a data$...
value. Next, I add the geom_bar()
statement and I have to use stat = "identity"
to tell ggplot
to use the actual values in my value
rather than trying to plot the count of the number.
Upvotes: 1
Reputation: 830
You have to use stat = "identity"
in geom_bar()
.
dat <- data.frame("cat" = c("A", "BC", "D"),
"val" = c(23, 12, 43))
ggplot(dat, aes(as.factor(cat), val)) +
geom_bar(stat = "identity") +
coord_flip()
Upvotes: 1