daddo
daddo

Reputation: 11

How do I plot a barplot using ggplot2 that differentiates subgroups by color for every year-observation?

I have a dataset that looks like this:

year  region  value

2000  Asia       15
2000  Europe     13
2000  America    17
2001  Asia       20
2001  Europe     19
2001  America    25

I need to plot a bar graph with year on the x-axis and value on the y-axis, using colors to differentiate the various regions.

I tried plotting it using ggplot2 like this:

ggplot(data = my_data, aes(x = year, y = value, fill = region)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  scale_fill_gradientn(colours = topo.colors(6))

I am able to differentiate the groups by their color, however I get that the groups are stacked for every year, while I would want them to be side by side. How can I do it?

I tried also this:

ggplot(data = my_data, aes(x = year, y = value, fill = region)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme_minimal() +
  scale_fill_gradientn(colours = topo.colors(6))

but everything becomes a mess, I don't know why.

Upvotes: 0

Views: 73

Answers (1)

zephryl
zephryl

Reputation: 17309

scale_fill_gradientn() is for continuous variables, but region is discrete (categorical). You can use scale_fill_manual() to specify your colors instead. Also, you can change year to a factor to avoid values like 2000.5 appearing on the x axis.

library(ggplot2)

my_data$year <- factor(my_data$year)

ggplot(data = my_data, aes(x = year, y = value, fill = region)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme_minimal() +
  scale_fill_manual(values = topo.colors(6))

Upvotes: 1

Related Questions