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

R语言绘图如何使用不同列分别做数据分段与图例、坐标轴文本展示

解决方案

你需要保持x轴的实际分组变量为唯一标识的device列避免聚合,仅修改x轴的显示标签为对应name列的值即可,不需要硬编码标签。

步骤1:修正长宽转换逻辑

转换长表时保留device和name两个字段,确保每个设备的name值可被后续调用:

threshold_colours <- usecol(pal = pal_seeblau, n = 3)

who_threshold_chart <-
  my_matrix %>% # 替换为你实际使用的数据集即可
  ungroup() %>%
  # 转换长表时排除device和name两列,保留所有维度信息
  gather("sum_temp", "hours", -c(device, name)) %>%

步骤2:修改x轴标签映射

ggplot的aes参数中x仍使用device保证分组唯一,新增scale_x_discrete()配置动态替换x轴标签:

ggplot(aes(x = device, y = hours, fill = factor(sum_temp))) +
  geom_bar(position="stack", stat="identity", width = 0.6, colour = "#e9ecef") +
  # 新增这段:动态映射device到对应的name作为x轴标签
  scale_x_discrete(labels = setNames(unique(my_matrix$name), unique(my_matrix$device))) +
  # 剩余原有配置保持不变
  scale_y_percent(limits = c(0, 1.0)) +
  theme_ipsum() +
  theme(axis.text.x = element_text(size = 7, angle = 60, hjust = 1),
        axis.text.y = element_text(size = 7),
        legend.position = "bottom",
        legend.title = element_text(size = 10),
        legend.text = element_text(size = 10)) +
  guides(fill = guide_legend(title = "Night-time temperature fell", title.position = "top"), drop = FALSE) +
  scale_fill_manual(values = threshold_colours, labels = c("below 12°C", "below 16°C", "below 18°C")) +
  xlab("") +
  ylab("of total night-time hours") +
  labs(fill = "")

实现逻辑

setNames()会自动生成键为device值、值为对应name的命名向量,scale_x_discrete的labels参数会自动匹配x轴的device取值,替换为对应的name显示。既不会触发重复name的聚合问题,也不需要硬编码标签,可适配任意数量的设备。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:15:04