Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

r - Add a dynamic title to plot based on value in another df

I have two dataframes, one that I used in the function below as the input and another one called abbreviations that contains two columns: the abrreviations for European cities(Abvr) and full names of the cities(Name).

What I want to do is add a dynamic title to my plot that looks for the full name of the city in the abbreviations dataframe. This name called "X" I then want to use in my function below. I'm struggling to find a way to add this. when I put in ggtitle(paste0("Storms in ",abbreviations$name))

It just chooses the first value of the column which is a random city, instead of the one that matches the city in my other dataframe.

I have the code below:

plot_by_city<- function(dataframe, city_name, color="red"){
data1 <- filter(dataframe, city == city_name)  
ggplot(data = data1, aes(x= scale, y= injuries)) + 
geom_point(position= "jitter",shape=23, fill= color, color="black", size=3)+
ggtitle(paste0("Storms in ",X))
}

A possible input would be plot_by_city((Dataframe,"AMS", "tan")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can subset a dataframe with the city_name argument

# Make data
df <- data.frame(
  x = runif(100, 0, 10),
  y = runif(100, 0, 10),
  city = sample(c("AMS", "NYC", "SF"), 100, replace = TRUE)
)

cities_df <- data.frame(
  abb = c("AMS", "NYC", "SF"),
  city_full = c("Amsterdam", "New York", "San Francisco")
)

# Plot function
plot_by_city<- function(dataframe, city_name, color="red"){
  data1 <- filter(dataframe, city == city_name)  
  city_full_name <- cities_df$city_full[cities_df$abb == city_name]
  
  ggplot(data = data1, aes(x = x, y = y)) + 
    geom_point(position= "jitter",shape=23, fill= color, color="black", size=3) + 
    labs(title = paste0("Storms in ", city_full_name))
}

plot_by_city(df, "NYC")

Storms in New York


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...