[英]Why are the bars at limits of ggplot geom_col not visible but the labels are?
I am trying to set the limits of a geom_col()
plot to include only specific dates.我正在尝试将
geom_col()
图的限制设置为仅包含特定日期。 However, when I attempt to set the limit with scale_x_date()
the bars for the end points disappear.但是,当我尝试使用
scale_x_date()
设置限制时, scale_x_date()
的条形消失了。 If the end points are moved, the new end points disappear.如果移动端点,新的端点就会消失。
library(ggplot2)
TestData <- data.frame(
"Date" = as.Date(c('2020-10-16','2020-10-17','2020-10-18', '2020-10-19', '2020-10-20')),
"Number" = c(5,3,2,4,1)
)
ggplot(TestData, aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
scale_x_date(limits = as.Date(c('2020-10-17','2020-10-19'))) +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
The above MWE generates the plot below.上面的 MWE 生成了下面的图。
The same issue occurs regardless of whether I use xlim()
or scale_x_date()
.无论我使用
xlim()
还是scale_x_date()
都会出现同样的问题。
I agree the best way to deal with this is to filter your data.我同意处理此问题的最佳方法是过滤您的数据。 You can do this with
dplyr
你可以用
dplyr
做到这dplyr
library(dplyr)
TestData %>%
filter(Date>='2020-10-17' & Date<='2020-10-19') %>%
ggplot(aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
You could also technically do it with a scale but it's kind of a hack.你也可以在技术上用秤来做,但这有点像黑客。 You just need to adjust the end points a bit to filter out the other geoms to make sure they get dropped.
您只需要稍微调整端点以过滤掉其他几何图形以确保它们被丢弃。
ggplot(TestData, aes(x = Date, y = Number, fill = 'red', col = 'white')) +
geom_col() +
scale_x_date(limits=as.Date(c('2020-10-17','2020-10-19')) + c(-.5, .5)) +
geom_text(aes(label=Number), vjust = -0.5) +
ylim(0,15)
This still generates a warning message about the dropped values.这仍然会生成有关删除值的警告消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.