繁体   English   中英

使用“yearmon”变量(ggplot)在 x 轴上显示标签

[英]Displaying labels on x-axis with "yearmon" variable (ggplot)

我试图在我的 x 轴上显示所有月份的值,它被格式化为“yearmon”变量

我的数据结构如下:

打印数据示例

dput(collective_action_monthly[1:4, ])

输出:

structure(list(collective_action = structure(c(2L, 2L, 2L, 2L
), .Label = c("0", "1"), class = "factor"), treatment_details = c("pre", 
"pre", "pre", "pre"), month_year = structure(c(2011.41666666667, 
2011.75, 2011.83333333333, 2011.91666666667), class = "yearmon"), 
    n = c(22L, 55L, 15L, 207L), collective_action_percentage = c(0.0124223602484472, 
    0.031055900621118, 0.00846979107848673, 0.116883116883117
    ), am = structure(c(2L, 2L, 2L, 2L), .Label = c("post", "pre"
    ), class = "factor")), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    treatment_details = "pre", .rows = structure(list(1:4), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

这是我使用条形图按月可视化趋势的代码:

ggplot(data = collective_action_monthly, aes(x = month_year, y = collective_action_percentage)) +
    geom_bar(stat = "identity", position=position_dodge()) + 
    scale_fill_grey() +
    ylab("percentage") + 
    theme(text=element_text(size=10)) + 
    theme(plot.title = element_text(size = 10, face = "bold")) +
    scale_y_continuous(labels = percent_format(accuracy = 1)) +
   theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  theme_bw()

产生: 在此处输入图像描述

但是,我想在 x 轴上显示所有月份,而不是只在 x 轴上显示三个月。 我还尝试在上面的代码中添加“scale_x_continuous(labels = 0:14,breaks = 0:14)”,但它仍然不显示月份: 在此处输入图像描述

理想情况下,我想生成如下图,但用几个月而不是几年。

在此处输入图像描述

zoo包包括scale_x_yearmon ,所以你可以这样做:

library(zoo)
library(ggplot2)

ggplot(data = collective_action_monthly, 
       aes(x = month_year, y = collective_action_percentage)) +
    geom_col(position = position_dodge(preserve = "single")) +
    scale_y_continuous(labels = scales::percent_format(accuracy = 1),
                       name = "percentage") +
    scale_x_yearmon(breaks = seq(2011.25, 2012, 1/12),
                    limits = c(2011.25, 2012)) +
    theme_bw(base_size = 10) +
    theme(plot.title = element_text(size = 10, face = "bold"),
          axis.text.x = element_text(angle = 90, vjust = 0.5)) 

在此处输入图像描述

ggplot没有内置yearmon刻度——看起来像zoo package 那样,但它没有一种方便的方法来指定“每月休息”——所以我建议转换为Date class 并使用scale_x_date 我已经删除了您的大部分theme内容,以使我所做的更改更加明显(主题似乎与问题无关)。

ggplot(data = collective_action_monthly, aes(x = as.Date(month_year), y = collective_action_percentage)) +
    geom_bar(stat = "identity", position=position_dodge()) + 
    scale_fill_grey() +
    scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
    ylab("percentage") + 
  theme_bw()

在此处输入图像描述

暂无
暂无

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

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