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

Modify x axis tick labels in R using gg plot

提问人:kartik trivedi 提问时间:9/4/2023 更新时间:9/4/2023 访问量:57

问:

我正在尝试使用 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 标签 轴标签

评论

0赞 Andy Baxter 9/4/2023
您好 Kartik,原因可能取决于您的数据是什么样子的。您能否在问题中放一个数据样本,我们可以用它来尝试找到解决方案?有关发布可用数据的一些提示,请参阅此处
0赞 kartik trivedi 9/4/2023
你好!数据类似于这个工作日<-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)

答:

0赞 Andy Baxter 9/4/2023 #1

由于工作日存储为数字,因此将其解释为连续刻度。您可以在调用中使用以下命令进行转换,然后代码的其余部分应按预期工作:factoraes

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