Search code examples
rggplot2axisfactors

ggplot missing plot with x-axis factor


The following works fine:

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()

but if I chance x_val to factor, I am getting blank plot and message:

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()

message:

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

I can obviously drop factor conversion, but I need it in order to replace labels of x axis with scale_x_discrete(breaks = 1:10,labels= my_df$labels). Here is where I borrowed it link

Any thoughts?


Solution

  • Can you just leave x_val as numeric and use scale_x_continuous(breaks = 1:10,labels= my_df$labels) instead?