简体   繁体   English

使用 ggplot2 绘制条形图

[英]Plotting a Bar chart using ggplot2

I tried plotting a barchart with variables "week_day "from my dataframe.我尝试从我的 dataframe 中绘制一个带有变量“week_day”的条形图。 The variable contains days of the week.该变量包含星期几。 This is the code I used:这是我使用的代码:

ggplot(data=df_activity)+geom_bar(mapping = aes(x=week_day,color=Totalhrs),fill= "blue")+
  labs(title ="Total Logins Across the Week") 

This is result I got.这是我得到的结果。

点击这里 . . What do I do for the variable in X-axis to be arranged in order and not alphabetically?我该怎么做才能使 X 轴中的变量按顺序排列而不是按字母顺序排列?

You need to convert week_days to a factor and specify the order you want it to take:您需要将week_days转换为一个因子并指定您希望它采取的顺序:

ggplot(df_activity) +
  geom_bar(aes(x = factor(week_day, levels = c("Monday", "Tuesday", "Wednesday", 
                          "Thursday", "Friday", "Saturday", "Sunday"))), 
               fill = "blue") +
  labs(x = "Week day", title ="Total Logins Across the Week") 

在此处输入图像描述


Dummy data made up to match plot in question与有问题的 plot 匹配的虚拟数据

df_activity <- data.frame(
  week_day = rep(c("Monday", "Tuesday", "Wednesday", "Thursday", 
      "Friday", "Saturday", "Sunday"), 
    times = c(120, 150, 148, 145, 125, 123, 118))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM