如何使position_dodge和scale_x_date一起工作? [英] How to make position_dodge and scale_x_date work together?
问题描述
使用ggplot2时遇到以下困难.我正在尝试创建一个具有时间序列数据集的条形图,该数据集既显示每个条形的值,又在x轴下显示一个不错的日期格式.问题是:
I've reached the following difficulty while using ggplot2. I am trying to create a bar chart with a time-series dataset displaying both the values for each bar AND a nice date format under the x-axis. The issue is that:
- 要设置在条形图中或上方,必须使用position_dodge,但是此功能仅允许使用非POSIXct变量
- x轴上日期的转到函数是scale_x_date,它需要一个POSIXct变量
我该如何解决这个问题?
How do I solve this issue?
df <- data.frame(period = c("2019-01-01", "2019-02-01","2019-01-01","2019-02-01"),
variable = c("A", "A", "B", "B"),
value = c(100,88, 99,77))
df$period_d <- as.POSIXct(df$period)
这很好(但x轴上没有日期).
This works well (but without dates in the x-axis).
ggplot(df, aes(x=period, y=value, group= variable, fill=variable))+
geom_col(position= "dodge")+
geom_text(aes(x=period, y=value,label=value),
position = position_dodge(1))
这很好,但是值放在错误的位置
This works well but with the value in the wrong place
ggplot(df, aes(x=period_d, y=value, group= variable, fill=variable))+
geom_col(position= "dodge")+
scale_x_datetime(labels=date_format("%b-%y"),
breaks = date_breaks("1 month"))
但是将两者混合是失败的.如果使用POSIXct变量,则标签将不在其应有的位置;如果使用字符变量,则会出现以下错误消息:无效的输入:time_trans仅适用于POSIXct类的对象"
But mixing the two is a failure. If using a POSIXct variable, the labels are not where they are meant to be and if using the character variable you reach this error message: "Invalid input: time_trans works with objects of class POSIXct only"
有什么想法吗?
推荐答案
有 datetimes 的POSIXct和 date 的Date类(没有时间戳).后者是离散的,因此您可以将其与条形图和躲闪一起使用.前者是连续的,所以你不能.
There is POSIXct for datetimes and the Date class for dates (without timestamps). The latter is discrete, so you can use it with barcharts and dodge; the former is continuous, so you can't.
df$date = as.Date(df$period_d)
ggplot(df, aes(x=date, y=value, group= variable, fill=variable))+
geom_col(position= "dodge")+
geom_text(aes(x=date, y=value,label=value),
# you are drawing one set of bars for every 30 days
# and geom_col is using the whole space by default.
position = position_dodge(width = 30)) +
scale_x_date()
您可以通过绘制更细的条来使其看起来更好:
You can make this look nicer by drawing thinner bars:
ggplot(df, aes(x=date, y=value, group= variable, fill=variable))+
geom_col(position= "dodge", width = 5)+
geom_text(aes(x=date, y=value,label=value),
# you are drawing one set of bars for every 30 days
position = position_dodge(width = 5)) +
scale_x_date()
这篇关于如何使position_dodge和scale_x_date一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!