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

如何用R的barplot()函数从原始CSV数据创建分组条形图

Got it, let's walk through how to make that grouped bar chart in R step by step. Here's exactly what you need to do:

Step 1: Format your data into a proper CSV file

First, save your data as a CSV with a clear column for the group labels. Create a file named scores.csv with this content:

Group,CT,VT,TT
A*,5.923076923,6.529411765,5.305555556
Not A*,5.555555556,6.434782609,5.352941176

Make sure this file is saved in your R working directory (you can check your current working directory with getwd()).

Step 2: Install and load required packages

We'll use the tidyverse package, which includes ggplot2 for plotting and tidyr to reshape your data. Run these lines (only install once if you don't have the package yet):

# Install the package (run once)
install.packages("tidyverse")

# Load the package every time you start R
library(tidyverse)

Step 3: Read the CSV into R

Import your data into an R data frame:

data <- read.csv("scores.csv", stringsAsFactors = FALSE)

Step 4: Reshape the data to long format

Grouped bar charts in ggplot2 work best with "long" formatted data (where each row represents a single observation). We'll convert your wide data to long using pivot_longer:

long_data <- data %>%
  pivot_longer(cols = -Group, names_to = "Metric", values_to = "Score")

This converts your CT/VT/TT columns into rows under a new Metric column, paired with their corresponding scores in the Score column.

Step 5: Create the grouped bar chart

Now use ggplot2 to build your chart:

ggplot(long_data, aes(x = Metric, y = Score, fill = Group)) +
  # Create grouped bars (position_dodge ensures they're side-by-side)
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # Add labels and title
  labs(
    title = "Scores by Metric and Group",
    x = "Metric",
    y = "Score",
    fill = "Group"
  ) +
  # Use a clean theme
  theme_minimal() +
  # Center the plot title
  theme(plot.title = element_text(hjust = 0.5))

If you want to customize the colors of the bars, add this line to the plot code:

scale_fill_manual(values = c("A*" = "#2c3e50", "Not A*" = "#7f8c8d"))

Just replace the hex codes with any colors you prefer.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:53:57