far
far

Reputation: 321

how can i have multiple barplots together in one plot

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

Answers (2)

Roman
Roman

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")

enter image description here

# 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)

enter image description here

Upvotes: 4

Olivia
Olivia

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()

enter image description here

Upvotes: 0

Related Questions