使用gg图修改R中的x轴刻度标签

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

我正在尝试使用scale_x_discrete修改ggplot中的x轴刻度标签,但是在执行它时,x轴刻度上没有显示任何内容。 我正在使用下面的代码

# a vector for weekdays
days_of_week<-c("sunday","monday","tuesday","wednesday","thursday","friday","saturday")

# calculating avderage ride time by the day of the week and user type
july_data%>%
  group_by(weekday,member_casual)%>%
  summarise(mean_ride_length = mean(as.numeric(ride_length)))%>%
  ggplot(aes(weekday, mean_ride_length, fill = member_casual))+
  geom_col(position = "dodge")+
  labs(title = "average ride time by weekday and rider type",
       x = "weekday",
       y = "average ride time (seconds)")+
  scale_x_discrete(labels = days_of_week)+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))
r ggplot2 label axis-labels
1个回答
0
投票

将工作日存储为数字后,会将其解释为连续刻度。您可以在

factor
调用中使用
aes
对其进行转换,然后代码的其余部分应该按预期工作:

library(tidyverse)

weekday <- c(6,7,1,5,2,3,4,7,1,2,5,4,6,7,3,4,7,6,5,2)
ride_length <- c(2000,1500,1425,528,1428,
                 5127,4218,6158,9998,10125,
                 528,2108,1486,50258,22858,
                 2052,10825,2206,1978,1742)

july_data <- tibble(weekday,
                    ride_length,
                    member_casual = sample(c("Member", "Casual"), 20,
                                           replace = TRUE))


# a vector for weekdays
days_of_week<-c("sunday","monday","tuesday","wednesday","thursday","friday","saturday")

# calculating avderage ride time by the day of the week and user type
july_data%>%
  group_by(weekday, member_casual)%>%
  summarise(mean_ride_length = mean(as.numeric(ride_length)))%>%
  ggplot(aes(factor(weekday), mean_ride_length, fill = member_casual))+
  geom_col(position = "dodge")+
  labs(title = "average ride time by weekday and rider type",
       x = "weekday",
       y = "average ride time (seconds)")+
  scale_x_discrete(labels = days_of_week)+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

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