我有一个 R 数据框。 第一列包括一年中的月份,从一月到十二月。第二列和第三列由具有或不具有某种特征的人的百分比组成。
我试图用 ggplot2 绘制两条线的线图。
ggplot(AZ, aes(x = Month)) +
geom_line(aes(y = AZ_yes, color = 'red')) +
geom_line(aes(y = AZ_no, color = 'lightblue'))
它给出了一个没有线条的空图
问题是什么?请帮忙
我无法运行你的代码,但重塑数据你可以得到绘图:
# Create the data frame
AZ <- data.frame(
Month = c("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"),
Yes = c(9, 8, 7, 11, 7, 11, 9, 8, 9, 10, 4, 7),
No = c(10, 8, 6, 10, 8, 10, 9, 9, 9, 7, 7, 7)
)
# Reshape data from wide to long format
AZ_long <- pivot_longer(AZ, cols = c(Yes, No), names_to = "Response", values_to = "Count")
# Convert Month to factor with correct order
AZ_long$Month <- factor(AZ_long$Month, levels = c("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"))
# Plot using ggplot
ggplot(AZ_long, aes(x = Month, y = Count, group = Response)) +
geom_line(aes(color=Response)) +
scale_color_manual(values = c("Yes" = "red", "No" = "lightblue"))