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

在R ggplot中创建多变量条形图:对比预期与观测值

Grouped Bar Chart for Expected vs Observed Values

Got it, let's create that grouped bar chart to compare expected vs observed values for each table. Here's a step-by-step solution using R's ggplot2 package (part of the tidyverse), which is ideal for this kind of visualization:

Step 1: Prepare Your Data

First, we'll convert your raw data into a tidy format that works best with ggplot2:

# Load the tidyverse package (includes ggplot2 and data manipulation tools)
library(tidyverse)

# Create your data frame from the provided values
data <- tibble(
  table_name = c("table1", "table2", "table3"),
  expected_value = c(95237608, 3014052, 3024749),
  observed_value = c(95100229, 3014052, 3024749)
)

# Reshape data from wide to long format (required for grouped bars)
tidy_data <- data %>%
  pivot_longer(
    cols = -table_name,  # Keep table_name as the identifier column
    names_to = "value_category",  # Name for the new category column
    values_to = "value"  # Name for the numeric values column
  )

Step 2: Generate the Grouped Bar Chart

Now we'll build the chart with side-by-side bars for each value category, plus some styling to make it clear and readable:

ggplot(tidy_data, aes(x = table_name, y = value, fill = value_category)) +
  # Add grouped bars with spacing between groups
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # Customize fill colors for clarity
  scale_fill_manual(
    values = c("expected_value" = "#2d3436", "observed_value" = "#0984e3"),
    labels = c("Expected Value", "Observed Value")  # Rename legend labels
  ) +
  # Add descriptive labels
  labs(
    title = "Expected vs Observed Values by Table",
    x = "Table Name",
    y = "Value",
    fill = "Metric"
  ) +
  # Clean, minimal theme with centered title
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title = element_text(size = 12),
    legend.title = element_text(size = 12),
    axis.text.y = element_text(size = 10)
  )

Notes on the Output:

  • For table2 and table3, the expected and observed values are identical, so their bars will overlap completely (you’ll only see one bar per table, but the legend will still show both categories).
  • The position_dodge argument ensures bars for each table are side-by-side instead of stacked.
  • You can adjust the width parameters and color values to match your preferred visual style.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:49:23