尝试绘制线图时得到空图

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

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

我试图用 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
2个回答
-1
投票

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

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


-1
投票

正如@Gregor指出的,你需要有

group
的审美。来自 ggplot 参考

群体审美默认设置为图中所有离散变量的相互作用。
这种选择通常会正确划分数据,但如果没有正确划分,或者图中没有使用离散变量,您将需要通过将组映射到每个组具有不同值的变量来显式定义分组结构。
[...] 默认情况下无法正确显示数据的常见情况有三种。
[...] 2. geom_line(),其中离散的 x 位置意味着组,而观察跨越离散的 x 位置。

玩具数据:

set.seed(100)

aux <- tibble(
  month = month(1:12, label = TRUE),
  yes = sample(5:15, 12, replace = TRUE),
  no = sample(5:15, 12, replace = TRUE)) 

较长的格式效果更好:

aux %>%
  pivot_longer(-month, names_to = "label", values_to = "value") %>% 
  
  ggplot() +
  geom_line(aes(x = month, y = value, group = label, color = label))  +
  scale_color_manual(values = c("yes" = "red", "no" = "lightblue")) + 
  theme_classic()

输出:

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