justlikearainbow
justlikearainbow

Reputation: 11

Single colored barchart

I have currently tried a course and would like to replicate it on my r-studio however, why can I only show a single color bar plot provided the code below? Is it related to the base color of the fill function? Thanks!

head(mtcars)
library(ggplot2)

# Bar chart
ggplot(mtcars, aes(x = cyl, fill = am)) +
  geom_bar(position = "fill")

# Convert bar chart to pie chart
ggplot(mtcars, aes(x = factor(1), fill = am)) +
  geom_bar(position = "fill") +
  facet_grid(. ~ cyl) + # Facets
  coord_polar(theta = "y") + # Coordinates
  theme_void() # theme

Upvotes: 1

Views: 75

Answers (1)

s__
s__

Reputation: 9485

Welcome to SO! I think you only need to add the group option to the aes():

ggplot(mtcars, aes(x = cyl, fill = am, group = am)) + geom_bar(position = "fill")

enter image description here

But maybe in this way it could be more readable:

ggplot(mtcars, aes(x = as.factor(cyl), fill = as.factor(am), group = as.factor(am))) +
  geom_bar(position = "fill") +
  xlab("CYL") +     # change x axis label
  labs(fill = "am") # change legend title

enter image description here

Upvotes: 1

Related Questions