我需要构建一个包含多个数据系列的图表,以根据特定元素(例如 P3、M1、M2 和 MC)比较每种动物的结果(例如“老马”与“新马”)。我想在一个清晰易懂的图表中可视化这些数据。您能否就最佳使用图表类型以及如何有效表示数据提出建议?我正在使用 Excel 和 R。
老马 | 骡子老 | 驴老了 | 都老了 | 新马 | 骡子新品 | 驴新 | 全新 | |
---|---|---|---|---|---|---|---|---|
P3 | 98.6 | 100 | 98.8 | 100 | 100 | 100 | ||
M1 | 80 | 100 | 80 | 100 | 100 | 100 | ||
M2 | 95 | 62.5 | 90.5 | 100 | 81.3 | 97.4 | ||
MC | 87.7 | 100 | 0 | 88.4 | 97.5 | 100 | 100 | 97.9 |
正如zx8754已经提到的,您可以使用melt函数来拉长数据表。然后我们可以添加类别(旧的和新的)和特定元素、组和图。请为可怜的驴子添加一些数据,否则结果会看起来很奇怪!
install.packages("reshape2", "tidyverse")
library(tidyverse)
library(reshape2)
# Original Data
data <- data.frame(
Horse_old = c(98.6, 80.0, 95.0, 87.7),
Mule_old = c(100.0, 100.0, 62.5, 100.0),
Donkey_old = c(NA, NA, NA, 0.0), # give values for donkey!
All_old = c(98.8, 80.0, 90.5, 88.4),
Horse_new = c(100.0, 100.0, 100.0, 97.5),
Mule_new = c(100.0, 100.0, 81.3, 100.0),
Donkey_new = c(100.0, 100.0, NA, 100.0), # give values for donkey!
All_new = c(100.0, 100.0, 97.4, 97.9)
)
# Reshape data for plotting
data_long <- melt(data,
variable.name = "Category",
value.name = "Value")
# Extract type (old/new) and animal from 'Category'
data_long <- data_long %>%
mutate(
Animal = gsub("_old|_new", "", Category),
Group = ifelse(grepl("old", Category), "Old", "New"),
Type = rep(c("P3", "M1", "M2", "MC"), times = 8) # Repeated for clarity
)
# Plot the data
ggplot(data_long, aes(x = Type, y = Value, color = Animal, group = interaction(Animal, Group))) +
geom_line(aes(linetype = Group), size = 1.2, alpha = 0.8) +
geom_point(size = 3, shape = 21, fill = "white") + # Adds points with clear centers
scale_linetype_manual(values = c("solid", "dashed")) + # Differentiate old vs new
scale_color_brewer(palette = "Set2") + # Add a distinguishable color palette
facet_wrap(~ Group, nrow = 2) +
theme_minimal() +
labs(
title = "Comparison of Old vs. New Values for Horses, Mules, and Donkeys",
x = "Type",
y = "Value"
) +
theme(
plot.title = element_text(size = 16, face = "bold"),
axis.text = element_text(size = 12),
axis.title = element_text(size = 14),
legend.title = element_text(size = 14),
legend.text = element_text(size = 12)
)