I have a melted data frame relating to 22 cities and for each city there are 5 size bands. The variable column relates to dates. The data frame looks like this:
City | size_band | variable | value |
---|---|---|---|
Madrid | 1 to 3 | April 2020 | 0.74 |
Madrid | 4 to 6 | April 2020 | 0.71 |
Madrid | 7 to 9 | April 2020 | 0.78 |
Madrid | 10 to 12 | April 2020 | 0.77 |
Madrid | 13 to 15 | April 2020 | 0.72 |
Madrid | 1 to 3 | May 2020 | 0.81 |
Madrid | 4 to 6 | May 2020 | 0.79 |
... | ... | ... | ... |
I'm trying to create a function that plots a time series using geom_point
for each city. I've tried the below code:
Cities_List<-split(data,
f = data$City)
# Function to plot different cities
plot.cities <- function(x) {
for (i in 1:length(Cities_List)) {
p<- x[[i]] %>%
ggplot(aes(variable, value))
geom_point(aes(color = size_band,
group = size_band),
size = 3,
shape = size_band)
}
}
plot.cities(Cities_list)
The color variable is not being recognised:
Error in geom_point(aes(color = size_band, group = size_band), size = 3, :
object 'size_band' not found
CodePudding user response:
aesthetics like color and shape must be mapped within the aes
function. Furthermore, function plot.cities
must return something instead of assigning an internal variable p
.
library(tidyverse)
data <- tibble::tribble(
~City, ~size_band, ~variable, ~value,
"Madrid", "1 to 3", "April 2020", 0.74,
"Madrid", "4 to 6", "April 2020", 0.71,
"Madrid", "7 to 9", "April 2020", 0.78,
"Madrid", "10 to 12", "April 2020", 0.77,
"Madrid", "13 to 15", "April 2020", 0.72,
"Madrid", "1 to 3", "May 2020", 0.81,
"Madrid", "4 to 6", "May 2020", 0.79
)
Cities_List <- split(data,
f = data$City
)
# Function to plot different cities
plot.cities <- function(x) {
for (i in 1:length(Cities_List)) {
x[[i]] %>%
ggplot(aes(variable, value))
geom_point(aes(color = size_band, shape = size_band), size = 3)
}
}
plot.cities(Cities_List)
Created on 2021-12-14 by the reprex package (v2.0.1)