如何在 Barplot 上显示 X 轴上的所有列?

How to display all columns on X axis on Barplot?

我正在尝试创建一个简单的条形图,在 x 轴上显示年份 (2008-2022),在 y 轴上显示推文数量。

但是,R 会自动“跳过”某些年份。有没有办法让每年都出现在相应栏下的 x 轴上?我试着玩“主题(axis.text.x = element_text(角度= 0,大小= 10))”,但没有任何改变。

这是我的代码:

ggplot(data, aes(x=created_at))+
  geom_bar(fill="steelblue")+
  theme_minimal() +
  labs(title="Number of Tweets per year", x="Year", y="Counts")


您可以通过以下两种方式实现这一目标:

  • 选项 1:如 @Axeman
  • 所述添加 + scale_x_continuous(breaks = 2008:2022)
  • 选项 2:将“created_at”更改为因子,可以直接在 ggplot().
  • 中完成

一些示例数据

set.seed(1)
n = sample(10:140, 15)
data <- tibble("created_at" = rep(2008:2022, n))

选项 1

ggplot(data, aes(x = created_at)) +
  geom_bar(fill = "steelblue") +
  theme_minimal() +
  labs(title = "Number of Tweets per year", x = "Year", y = "Counts") +
  scale_x_continuous(breaks = 2008:2022)

选项 2

ggplot(data, aes(x = factor(created_at))) +
  geom_bar(fill = "steelblue") +
  theme_minimal() +
  labs(title = "Number of Tweets per year", x = "Year", y = "Counts")