尝试在 R 中绘制线图时出现空图

问题描述 投票:0回答:1

我有一个 R 数据框。 第一列包括一年中的月份,从一月到十二月。第二列和第三列由具有或不具有某种特征的人的百分比组成。

我试图用 ggplot2 绘制两条线的线图。

    ggplot(AZ, aes(x = Month)) +
geom_line(aes(y = AZ_yes, color = 'red')) + 
geom_line(aes(y = AZ_no, color = 'lightblue')) 

它给出了一个没有线条的空图

问题是什么?请帮忙

r ggplot2 line-plot
1个回答
0
投票

我无法运行你的代码,但重塑数据你可以得到绘图:

# 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"))

© www.soinside.com 2019 - 2024. All rights reserved.