【问题标题】:Set axis limits in ggplot2 using pipes and fredr使用管道和 fredr 在 ggplot2 中设置轴限制
【发布时间】:2022-11-13 21:49:01
【问题描述】:

我正在尝试使用 fredr 包和管道 (%>%) command in ggplot2. I am struggling to use the xlim()orlims()` 命令使用 St Louis Fed 数据绘制图。

我可以使用以下代码轻松生成我想要的图(但没有正确的图限制)。

#libraries
library(tidyverse)
library(fredr)
library(ggthemes)

#make the plot

map_dfr(c("LABSHPUSA156NRUG", "W273RE1A156NBEA"), fredr) %>%

pivot_wider(
   names_from = series_id, 
   values_from = value) %>%

mutate(., labour_share_of_profit = LABSHPUSA156NRUG/W273RE1A156NBEA) %>%
 
ggplot(data = ., mapping = aes(x = date, y =labour_share_of_profit)) +
geom_line(lwd=1.2) +
labs(x = "Year", y = "Share of Labour Compensation as Proportion of Profit") +
theme(legend.position = "none") +
theme_wsj()

%>%

{ggsave(filename = "p1_wsj.pdf", 
     device = "pdf",
     width = 10*sqrt(2), height = 10)
 }

这将产生以下图。

现在,如何使用 xlim() 函数来设置系列开头的情节限制?

【问题讨论】:

  • 下次请用df <- dput() 做一个可重现的例子。

标签: r ggplot2 pipe


【解决方案1】:

类似下面的内容将允许您设置自定义标签范围(尽管它不会限制/过滤数据):

ggplot(data = ., mapping = aes(x = date, y =labour_share_of_profit)) +
geom_line(lwd=1.2) +
scale_x_continuous(breaks=1950:2020) +
labs(x = "Year", y = "Share of Labour Compensation as Proportion of Profit") +
theme(legend.position = "none") +
theme_wsj()

【讨论】:

    【解决方案2】:

    只需使用coord_cartesian。您可以在此处设置 x 轴和 y 轴的范围。例如xlim = c(1950,2020)

    ggplot(data = ., mapping = aes(x = date, y =labour_share_of_profit)) +
    geom_line(lwd=1.2) +
    labs(x = "Year", y = "Share of Labour Compensation as Proportion of Profit") +
    theme(legend.position = "none") +
    theme_wsj() +
    coord_cartesian(xlim = c(1950,2020))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多