Reputation: 321
I have a problem with having barplot of my data. I consider a data sample like this:
data <- data.frame(P=sample(c("A","B","C","D") , 10,replace = TRUE) ,O=c(2009,1299,4876,3258,1324,3609,2176,4076,2314,6590), X=c(4754,9800,7600,1760,2840,3710,3708,9126,7777,8220))
data <- data %>%
group_by(P) %>%
summarize(mean_O=mean(O),mean_X=mean(X))
Now I want to have a barplot which x.axis represents P variable and in y.axis have both the mean_O and mean_X values. In other words, I want to have mean_X and mean_O for each type of P variable both together in one graph.
How can I have this plot with ggplot()+geom_bar
?
Any little help would be greatly appreciated.
Upvotes: 2
Views: 11815
Reputation: 17648
You can try:
# read your data
d <- read.table(text="insurerType x1 x2 x3
a 12 14 15
b 10 15 10
c 7 23 0", header=T)
# load ggplot2 and dplyr within
library(tidyverse)
# transform the data using dplyr and tidyr and plot the bars using fill to
# get the three bars per insurer. I used geom_col as it uses stat_identity as default
d %>%
gather(key, value, -insurerType) %>%
ggplot(aes(x=insurerType, y=value, fill = key)) +
geom_col(position = "dodge")
# Another solution would be to use a facet like this:
d %>%
gather(key, value, -insurerType) %>%
ggplot(aes(x=key, y=value, fill=key)) +
geom_col(position = "dodge") +
facet_wrap(~insurerType)
Upvotes: 4
Reputation: 814
Reshape the data first
library(reshape2)
df2 = melt(df)
Then Plot
library(ggplot2)
ggplot(data=df2, aes(x=insurerType, y=value, fill=variable)) +
geom_bar(stat="identity", color="black", position=position_dodge())+
theme_minimal()
Upvotes: 0