In R, How to manipulate (using manipulate pkg) the

2019-07-28 06:48发布

问题:

Using this as a starting point: ggplot/mapping US counties — problems with visualization shapes in R

I wanted to add a manipulate control for the fill variable. Something similar to this:

if (!require("pacman")) install.packages("pacman")
pacman::p_load(ggplot2, XLConnect, rgdal, RColorBrewer, data.table, mapproj, manipulate)

#additional lines
county.data[obesity.data,obesity09:=PCT_OBESE_ADULTS09]
county.data[obesity.data,obesity10:=PCT_OBESE_ADULTS10]
county.data[obesity.data,obesity13:=PCT_OBESE_ADULTS13]

manipulate({ggplot(map.df, aes(x=long, y=lat, group=group, fill=ObesityYear)) +
scale_fill_gradientn("",colours=brewer.pal(9,"YlOrRd"))+
geom_polygon()+coord_map()+
labs(title="2010 Adult Obesity by County, percent",x="",y="")+
theme_bw()}, ObesityYear = picker("obesity09", "obesity10", "obesity13"))

But of course, the ggplot does not recognize the ObesityYear variable as part of the dataframe and gives the error:

Error in eval(expr, envir, enclos) : object 'ObesityYear' not found

EDIT AFTER COMMENTS LED TO RESOLUTION

manipulate({ggplot(map.df, aes_string(x='long', y='lat', group='group', fill=ObesityYear)) + 
    geom_polygon()+coord_map()+ 
    theme_bw()}, ObesityYear = picker('obesity09', 'obesity10', 'obesity13'))

回答1:

For this to work you need to use aes_string in order to be able to use string choices in the picker function.

Look at this example:

#example data.table
set.seed(5)
dt <- data.table(a = runif(10), 
                 b = runif(10), 
                 fillvar1 = factor(sample.int(2,20, rep=T)), 
                 fillvar2 = factor(sample.int(2,20, rep=T)),
                 fillvar3 = factor(sample.int(2,20, rep=T)))

Solution:

library(manipulate)
manipulate({   
    ggplot(dt, aes_string('a', 'b', colour=choose_var )) + geom_point()},
    choose_var = picker('fillvar1','fillvar2','fillvar3'))

It is hard to upload a picture to show the interactivity but you will notice in the above code that every time you select a different value, the colours of the points will change accordingly.



标签: r ggplot2