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

如何用R基于种族比例频率表绘制年份维度的折线图?

How to Create a Yearly Race/Ethnicity Proportion Line Plot in R

Hey there! Great job getting your proportion table set up with prop.table()—you're already halfway there. To make that line plot with years on the x-axis and each race/ethnicity as a separate line, we just need to get your data into a plot-friendly format and then use either ggplot2 (for polished, customizable plots) or base R (no extra packages needed). Let's break both methods down:


First, we'll convert your matrix perrace into a long-format data frame (ggplot2 works best with this structure). We'll use the tidyr package for reshaping, and scales to format the y-axis as percentages.

Step 1: Prepare the Data

# Install packages first if you haven't: install.packages(c("ggplot2", "tidyr", "scales"))
library(ggplot2)
library(tidyr)
library(scales)

# Convert the proportion matrix to a data frame and keep race names as a column
perrace_df <- as.data.frame(perrace)
perrace_df$race <- rownames(perrace_df)  # Add race names as a dedicated column
rownames(perrace_df) <- NULL  # Remove redundant row names

# Reshape from wide to long format (one row per race-year combination)
perrace_long <- pivot_longer(perrace_df,
                             cols = -race,  # Keep the race column, reshape all year columns
                             names_to = "year",
                             values_to = "proportion")

# Convert year from character to numeric (so ggplot treats it as a continuous variable)
perrace_long$year <- as.numeric(perrace_long$year)

Step 2: Create the Line Plot

ggplot(perrace_long, aes(x = year, y = proportion, color = race, group = race)) +
  geom_line(linewidth = 1.2) +  # Thicken lines for better readability
  geom_point(size = 2.5) +      # Add points to highlight exact yearly values
  scale_y_continuous(labels = percent_format(accuracy = 1)) +  # Show y-axis as percentages
  labs(
    title = "Race/Ethnicity Proportions Over Time",
    x = "Year",
    y = "Proportion of Population",
    color = "Race/Ethnicity"
  ) +
  theme_minimal()  # Clean, modern theme (swap with theme_bw() for a classic look)

This gives you a polished plot with automatic legends, easy-to-read axes, and tons of room to tweak colors or themes later.


Method 2: Using Base R (No Extra Packages)

If you prefer not to load external packages, base R can handle this too. We'll plot each race's line manually and add a legend to clarify which line corresponds to which group.

# Convert year column names to numeric values
years <- as.numeric(colnames(perrace))

# Initialize the plot with the first race's data
plot(years, perrace["Other", ],
     type = "l",  # Start with a line
     col = "#E63946",  # Red for "Other"
     xlab = "Year",
     ylab = "Proportion",
     ylim = c(0, 0.5),  # Set y-axis range to fit all values
     main = "Race/Ethnicity Proportions Over Time",
     lwd = 2)  # Line width

# Add lines for the remaining races
lines(years, perrace["Latino", ], col = "#457B9D", lwd = 2)
lines(years, perrace["non-hispanic black", ], col = "#1D3557", lwd = 2)
lines(years, perrace["non-hispanic white", ], col = "#A8DADC", lwd = 2)

# Add points to each line for clarity
points(years, perrace["Other", ], col = "#E63946", pch = 16)
points(years, perrace["Latino", ], col = "#457B9D", pch = 16)
points(years, perrace["non-hispanic black", ], col = "#1D3557", pch = 16)
points(years, perrace["non-hispanic white", ], col = "#A8DADC", pch = 16)

# Add a legend to identify each line
legend("topleft",
       legend = rownames(perrace),
       col = c("#E63946", "#457B9D", "#1D3557", "#A8DADC"),
       lty = 1,  # Line type
       pch = 16,  # Point type
       lwd = 2)

Either method will produce the line plot you're looking for. The ggplot2 approach is more flexible if you want to adjust colors, labels, or themes down the line!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:23:14