You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写以城市名为输入的ggplot+dplyr棒棒糖图函数?

封装按城市过滤的棒棒糖图绘制函数

基于你提供的数据框和绘图逻辑,可将其封装为一个接收城市名称作为参数的函数,代码实现如下:

# 确保加载依赖包
library(dplyr)
library(ggplot2)

# 定义绘图函数
plot_city_lollipop <- function(target_city) {
  df %>% 
    filter(cities == target_city) %>%
    ggplot(aes(x = variables, y = values)) +
    geom_segment(aes(x=variables, xend=variables, y=0, yend=values), color="skyblue") +
    geom_point(color="blue", size=4, alpha=0.6) +
    coord_flip() +
    labs(title = paste(target_city, "城市指标棒棒糖图")) # 可选:添加图表标题
}

调用示例

要绘制指定城市的图表,直接传入城市名称字符串即可:

# 绘制C2城市的棒棒糖图
plot_city_lollipop("C2")

# 绘制C3城市的棒棒糖图
plot_city_lollipop("C3")

注意事项

  • 参数target_city需传入与数据框中cities列匹配的字符串(如"C1"、"C2")
  • 调用函数前需确保数据框df已存在于当前R环境中
  • 若不需要图表标题,可删除函数内的labs代码行

内容的提问来源于stack exchange,提问作者rez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:25:08