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

如何将R基础barplot转换为ggplot并解决列求和数据转置问题

解决方案

你不需要使用t()做转置操作,colSums返回的是携带列名的数值向量,直接将其转换为两列的长格式数据框即可适配ggplot的输入要求,完整修改后的代码如下:

## 提取指标列
indicators <- clean_data[c(8, 12, 14:23)]

## 计算各列总和
indicator_sums <- colSums(indicators, na.rm = TRUE)

### 转换为ggplot适用的长格式数据框
indicator_df <- data.frame(
  indicator_name = names(indicator_sums),
  sum_value = indicator_sums,
  row.names = NULL
)

## ggplot版本柱状图
library(ggplot2)

ggplot(indicator_df, aes(x = indicator_name, y = sum_value)) +
  geom_col(fill = "magenta") +
  labs(y = "Offences Recorded Using Indicator", x = NULL) +
  scale_y_continuous(limits = range(pretty(c(0, indicator_df$sum_value)))) +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1, size = 7),
    axis.text.y = element_text(size = 7.5),
    axis.title.y = element_text(size = 8)
  )

补充说明

如果确实需要通过转置原始数据的方式计算总和,可使用如下写法替代colSums加数据框转换的步骤:

indicator_df <- as.data.frame(t(indicators)) %>%
  rowwise() %>%
  summarise(
    indicator_name = cur_column(),
    sum_value = sum(c_across(everything()), na.rm = TRUE)
  )

原来的t()转置后得到的是行、列倒置的矩阵,没有做聚合计算,也未转换为ggplot要求的分类值、数值分别为独立列的结构化数据框,因此无法直接用于绘图。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:06