ggplot缺少x轴因子的图

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

以下功能正常:

my_df <- data.frame(x_val = 1:10, y_val = sample(1:20,10), 
            labels = sample(c("a", "b"), 10, replace = T))
ggplot(data = my_df, aes(x = x_val, y = y_val)) + geom_line()

但是如果我有机会将x_val分解为因子,则会得到空白的图和消息:

my_df <- data.frame(x_val = 1:10, y_val = sample(1:20,10), 
          labels = sample(c("a", "b"), 10, replace = T))
my_df$x_val <- as.factor(my_df$x_val)
ggplot(data = my_df, aes(x = x_val, y = y_val)) + geom_line()

消息:

geom_path: Each group consists of only one observation. Do you
need to adjust the group aesthetic?

我显然可以放弃factor转换,但是我需要用scale_x_discrete(breaks = 1:10,labels= my_df$labels)替换x轴的标签。这是我借的地方link

有什么想法吗?

r ggplot2 axis factors
1个回答
1
投票

您能否只将x_val保留为数字并改用scale_x_continuous(breaks = 1:10,labels= my_df$labels)

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