0
votes

I have a data set of transactions regarding resale flats.

I used the pipeline function to group and summarise the data based on the flat_type and region

plotdata1<-data1 %>% 
  group_by(year, region,flat_type) %>% 
  summarize(mean_price = mean(resale_price))

Here's my data set

 year region  flat_type mean_price
  <int> <fct>   <fct>          <dbl>
1  2007 Central 3 ROOM       236452.
2  2007 Central 4 ROOM       367471.
3  2007 Central 5 ROOM       467264.
4  2007 East    3 ROOM       198682.
5  2007 East    4 ROOM       266645.
6  2007 East    5 ROOM       323110.

However, this does not allow me to plot the line graph correctly as there are 2 grouping variables. I intend to plot the average resale prices of flats based on their region including all 3 flat-types. Using shiny I will then be able to use the selectInputfunction to select between all flat-types or each individual flat-type. For example, the graph will be able to show the average resale price of 3 room flats in each region.

Here the code for the plot

ggplot(data=plotdata1,aes(x=year,y=mean_price))+
  geom_line(stat = 'identity',aes(colour=region,group=region))+
  geom_point()+
  xlim(c(2006,2018))+
  ylab("Average Price")+
  xlab('Year')

Which gives me the error

Error: Column region can't be modified because it's a grouping variable

Doing this instead works and plots them based on the region but then I will not be able to select between each flat-type from the input boxes.

plotdata1<-data1 %>% 
  group_by(year, region) %>% 
  summarize(mean_price = mean(resale_price))

Here's the intended look for the plot which works when using the pipeline code above this picture. But then again I will not be able to select between either all flat-types or each flat-type

1
Maybe try ungroup() after the summarize? - cardinal40

1 Answers

-1
votes

Hmm not sure why you are getting that error. Can you try the call putting aes() inside the ggplot() call instead of the geom? This works for me...

set.seed(123)
df <- data.frame(region=sample(letters[1:4],100,T),
                 type=sample(c('1 room','2 room','3 room'),100,T),
                 year=sample(2010:2015,100,T),
                 price=sample(1000:2000,100,T))

df %>% group_by(region,type,year) %>% 
  summarise(mean.price=mean(price)) %>% 
  ggplot(aes(year,mean.price,group=region,color=region)) + geom_point() + geom_line() +
  facet_wrap(~type,scales='free')

graph

If you are using shiny, then you can remove the facet_wrap and add filter() before the ggplot call so that users can specify which type of room prices to plot.