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

如何用R绘制带零值参考竖线的水平条形图以展示各得分指标的均值

Solution for Horizontal Bar Chart of Score Means in R

Hey there! As someone new to R, I totally get wanting to create a clear, informative chart like this. Let's walk through step-by-step how to build exactly what you need using ggplot2—it's the go-to package for great visualizations in R.

Step 1: Prepare Your Data

First, let's get your dataset into R. You can create it directly using data.frame():

# Create your dataset
df <- data.frame(
  ID = 1:5,
  score1 = c(200, 250, 210, 220, 150),
  score2 = c(300, -310, 400, -10, -50),
  score3 = c(400, -470, 480, -400, 400),
  score4 = rep(-200, 5)
)

Step 2: Calculate Mean Values & Reshape Data

ggplot2 works best with "long-form" data, so we'll first calculate the mean for each score, then convert the data from wide to long format. We'll use the dplyr and tidyr packages for this (install them first if you haven't with install.packages(c("dplyr", "tidyr", "ggplot2"))):

# Load required packages
library(dplyr)
library(tidyr)
library(ggplot2)

# Calculate mean scores and reshape data
mean_scores <- df %>%
  select(-ID) %>%  # Remove the ID column since we don't need it for means
  pivot_longer(cols = everything(), names_to = "Score_Indicator", values_to = "Score_Value") %>%
  group_by(Score_Indicator) %>%
  summarise(Mean_Score = mean(Score_Value))

Step 3: Create the Horizontal Bar Chart

Now we'll build the chart with the 0-value reference line, and bars that extend left/right based on mean sign:

# Build the visualization
ggplot(mean_scores, aes(x = Mean_Score, y = Score_Indicator)) +
  # Add vertical dashed reference line at 0
  geom_vline(xintercept = 0, color = "gray50", linetype = "dashed", linewidth = 1) +
  # Add horizontal bars (use stat = "identity" since we already have mean values)
  geom_bar(stat = "identity", fill = "#3498db", width = 0.7) +
  # Customize labels and title
  labs(
    title = "Mean Values of Score Indicators",
    x = "Mean Score Value",
    y = "Score Indicator"
  ) +
  # Use a clean theme and adjust text styling
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12)
  )

What This Does:

  • The geom_vline() adds the vertical reference line at 0, making it easy to compare positive/negative means.
  • Bars will automatically extend right for positive mean values and left for negative ones, exactly as you requested.
  • The theme_minimal() gives a clean, modern look, and we've adjusted text styles to make the chart readable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:57:40