ggplot技术问询:如何从两列取值并仅绘制苹果的Production指标?
解决你的ggplot筛选与绘图问题
嘿,我来帮你搞定这两个需求!咱们一步步来:
一、仅绘制苹果行的Production数据
首先看你的现有代码,目前是筛选了“Chillies and peppers, green”的行并绘制Y2014的数据。要只画苹果的Production数据,分两种常见数据结构来处理:
情况1:Production是单独的列名
如果你的CSV里,每个Item(比如apple)对应一行,且Production是一个独立列(和Area harvested、Yield并列),那直接筛选Item为apple的行,指定y轴为Production即可:
library(tidyverse) # 无需重复加载dplyr,tidyverse已经包含它了 # 读取数据 df <- read.csv("C:/Users/....data.csv", encoding = "ASCII", header = TRUE, sep = "," ) # 筛选苹果行并绘制Production数据 ggplot(subset(df, Item == "apple"), aes(x = Area, y = Production)) + geom_bar(stat = "identity", width = 0.6) + coord_flip()
情况2:Production是参数列的一个值
如果你的数据是长格式(比如有一列叫Parameter,值包含"Area harvested"、"Yield"、"Production"),那需要同时筛选Item和Parameter:
ggplot(subset(df, Item == "apple" & Parameter == "Production"), aes(x = Area, y = Y2014)) + geom_bar(stat = "identity", width = 0.6) + coord_flip()
这样就只会画出苹果的Production对应的数据,不会同时显示三个参数啦。
二、在ggplot中从两个不同列筛选取值
这个需求分两种常见场景,我都给你举例:
场景1:基于两个列的条件筛选行
比如你想筛选Area大于某个数值、同时Production超过阈值的苹果行,用dplyr的filter函数(tidyverse自带)可以轻松实现多列条件筛选:
# 筛选Item为apple,且Area>100、Production>500的行 ggplot(df %>% filter(Item == "apple", Area > 100, Production > 500), aes(x = Area, y = Production)) + geom_bar(stat = "identity", width = 0.6) + coord_flip()
- 逗号分隔表示“且”的关系,用
|可以表示“或”的关系(比如Area>100 | Production>500)。
场景2:同时使用两个列的数据绘图
如果你想把两个不同列(比如Yield和Production)的数据放在同一个图里对比,先把数据转成长格式再绘图更方便:
# 把Yield和Production转成长格式,统一为Metric和Value列 df_long <- df %>% filter(Item == "apple") %>% pivot_longer(cols = c(Yield, Production), names_to = "Metric", values_to = "Value") # 同时绘制两个列的数据,用fill区分 ggplot(df_long, aes(x = Area, y = Value, fill = Metric)) + geom_bar(stat = "identity", width = 0.6, position = "dodge") + coord_flip()
这样就能清晰对比两个指标的数据了。
内容的提问来源于stack exchange,提问作者Raul
相关产品推荐
相关产品推荐

