简体   繁体   中英

Using R and ggplot2 how do I create a graph with multiple columns

My R data frame ( electronics ) look like this:

date                  manufacture    price
2019-11-22 11:30:04   Apple          600.00
2019-01-16 01:74:14   Samsung        877.00
2019-07-12 04:23:31   Apple          925.00
2019-07-12 01:21:54   Apple          1200.00
2019-01-16 04:48:34   Samsung        1100.00
2019-07-12 12:20:22   Apple          1450.00    
2019-03-28 06:23:11   Apple          1250.00

What I want to do are the following:

  • Take the sum of price for each given day ( date ) and create a chart to see the sale of each Manufacture by date
  • date is going to be on x-axis and line plot that has the price of manufacture
  • Basically I want to see the chart sum of sales overtime per the manufacture.

What did I do?

ggplot(electronics,
   aes(date,sum(price))) +
   geom_point() + 
   geom_smooth(method="lm") +
   facet_grid(manufacture)

However, it seems like I am not getting proper chart. Please kindly help me solve this. Thank you!

I tried the following according to your data:

library(tidyverse)
electronics <- data.frame(date = c("2019-11-22 11:30:04",
"2019-01-16 01:74:14", "2019-07-12 04:23:31",
"2019-07-12 01:21:54", "2019-01-16 04:48:34",
"2019-07-12 12:20:22", "2019-03-28 06:23:11"), 
manufacture = c("Apple","Samsung","Apple","Apple",
"Samsung","Apple","Apple"), 
price = c(600,877,925,1200,1100,1450,1250))

electronics$date <- as.Date(electronics$date)

electronics %>% group_by(date,manufacture) %>% 
summarise(sum = sum(price)) %>% ggplot(aes(date,sum)) + 
geom_point() + geom_smooth(method="lm") + facet_grid(~manufacture)

As per your question and observation I have edited the code so now you can aggregate with "group_by", in this case by date and manufacture. After that, you summarise the sum of the prices.

在此处输入图像描述

Hope it helps. Regards,

Alexis

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