编辑:如何转换为因子变量以对图上的时间数据进行排序

EDIT: How to convert to factor variable to order Time data on plot

EDIT ::: 我希望 X 轴上的值按时间顺序排列在 AM 和 PM 组中。所以 1:00AM - 11:00AM 12:00PM - 9:00PM

我知道这与将我的 ActivityHoursII 变量更改为一个因子有关。但是我不确定执行此操作的步骤。

目前: factorintensities <- factor(hourlyIntensitiesclean$ActivityHour) 水平(因子强度) 1 "4/12/2016 1:00:00 上午" "4/12/2016 1:00:00 下午" "4/12/2016 10:00:00 上午" "4/12/2016 10:00:00 私信” [5] "4/12/2016 11:00:00 AM" "4/12/2016 11:00:00 PM" "4/12/2016 12:00:00 AM" "4/12/2016 12:00:00下午" [9] "4/12/2016 2:00:00 上午" "4/12/2016 2:00:00 下午" "4/12/2016 3:00:00 上午" "4/12/2016 3:00:00下午" [13] "4/12/2016 4:00:00 上午" "4/12/2016 4:00:00 下午" "4/12/2016 5:00:00 上午" "4/12/2016 5:00:00下午" [17] "4/12/2016 6:00:00 上午" "4/12/2016 6:00:00 下午" "4/12/2016 7:00:00 上午" "4/12/2016 7:00:00下午" [21] "4/12/2016 8:00:00 上午" "4/12/2016 8:00:00 下午" "4/12/2016 9:00:00 上午" "4/12/2016 9:00:00下午

我希望只有两个级别.. AM 的所有数据和 PM 的所有数据。该功能无效

factorintensities <- factor(hourlyIntensitiesclean$ActivityHour, levels = "AM", "PM")

这是我的图表代码

ggplot(data=hourlyIntensities_mergedclean) +
geom_point(mapping = aes(x = ActivityHoursII, y = AverageIntensity)) +
theme(axis.text.x = element_text(angle = 45))

dplot

structure(list(Id = c("user_1", "user_1", "user_1", "user_1", 
"user_1", "user_1", "user_1", "user_1", "user_1", "user_1"), 
ActivityHour = c("4/12/2016 12:00:00 AM", "4/12/2016 1:00:00 AM", 
"4/12/2016 2:00:00 AM", "4/12/2016 3:00:00 AM", "4/12/2016 4:00:00 AM", 
"4/12/2016 5:00:00 AM", "4/12/2016 6:00:00 AM", "4/12/2016 7:00:00 AM", 
"4/12/2016 8:00:00 AM", "4/12/2016 9:00:00 AM"), TotalIntensity = c(20, 
8, 7, 0, 0, 0, 0, 0, 13, 30), AverageIntensity = c(0.333333, 
0.133333, 0.116667, 0, 0, 0, 0, 0, 0.216667, 0.5), ActivityHouredit = c("12:00:00 AM", 
"1:00:00 AM", "2:00:00 AM", "3:00:00 AM", "4:00:00 AM", "5:00:00 AM", 
"6:00:00 AM", "7:00:00 AM", "8:00:00 AM", "9:00:00 AM"), 
ActivityHoursII = c("12:00:00 AM", "1:00:00 AM", "2:00:00 AM", 
"3:00:00 AM", "4:00:00 AM", "5:00:00 AM", "6:00:00 AM", "7:00:00 AM", 
"8:00:00 AM", "9:00:00 AM")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

df 成为数据的名称。

方法一

我们可以先指定坐标轴的顺序。

axisorder <- c("1:00:00 AM","2:00:00 AM","3:00:00 AM","4:00:00 AM","5:00:00 AM","6:00:00 AM","7:00:00 AM", "8:00:00 AM", "9:00:00 AM", "12:00:00 AM")

然后在 scale_x_discrete 函数中使用 limits 参数对轴重新排序。

ggplot(data=df) +
  geom_point(mapping = aes(x = ActivityHoursII, y = AverageIntensity)) +
  theme(axis.text.x = element_text(angle = 45)) +
  scale_x_discrete(limits = axisorder)

方法二

或者,我们可以将列更改为因子并赋予它水平。

df$ActivityHoursII <- factor(df$ActivityHoursII, levels = axisorder)

然后在没有 scale_x_discrete

的情况下绘制它
ggplot(data=df) +
  geom_point(mapping = aes(x = ActivityHoursII, y = AverageIntensity)) +
  theme(axis.text.x = element_text(angle = 45))

我们可以得到情节: