简体   繁体   中英

how to plot a histogram using ggplot2 with a slightly different data

I would like to plot the (histogram) number of cars on y axis and value on x axis. Could you please help me with this.

I tried

ggplot(a, aes(x=value, y=cars, fill=type)) + geom_histogram()

cars  type  company  value
car1 all company1  0.4
car2 all  company1  0.6
car3 all  company1  1
car1 one company1  1.2
car1 one  company1  0.1
car2 one company1  0.1
car3 one  company1  0.9
car1 one  company1  0.44
car2 one  company2  0.55
car3 one company2  0.1
car1 one  company2  0
car1 one  company3  0
car2 one  company3  1
car3 one  company3  1.2

You need to do the following to have what you want:

a <- read.table(header=T ,  text="cars  type  company  value
car1 all company1  0.4
car2 all  company1  0.6
car3 all  company1  1
car1 one company1  1.2
car1 one  company1  0.1
car2 one company1  0.1
car3 one  company1  0.9
car1 one  company1  0.44
car2 one  company2  0.55
car3 one company2  0.1
car1 one  company2  0
car1 one  company3  0
car2 one  company3  1
car3 one  company3  1.2")

library(dplyr) #you need the following line to aggregate your data per car and find mean and counts
aggregated_data <- a %>% group_by(cars) %>% summarise( mean = mean(value), counts = length(value) ) 

#view aggregated data
> aggregated_data
Source: local data frame [3 x 3]

  cars      mean counts
1 car1 0.3566667      6
2 car2 0.5625000      4
3 car3 0.8000000      4

#plot
ggplot(aggregated_data, aes(y = counts , x = mean , fill=cars ) ) + geom_bar(stat='identity')

在此处输入图片说明

And that's what you want!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM