【问题标题】:Fitting a plot with multi-line y labels用多线 y 标签拟合图
【发布时间】:2017-04-07 14:40:51
【问题描述】:

我正在 R 中实现此分析:下载数据集,创建动物园对象并绘制数据集。

library(tseries)
library(zoo)

start <- "2011-01-01"
end <- "2014-12-31"

MET <- get.hist.quote("MET", quote="Close", start=start, end=end)
MHK <- get.hist.quote("MHK", quote="Close", start=start, end=end)
MJN <- get.hist.quote("MJN", quote="Close", start=start, end=end)
MKC <- get.hist.quote("MKC", quote="Close", start=start, end=end)
MLM <- get.hist.quote("MLM", quote="Close", start=start, end=end)
MMC <- get.hist.quote("MMC", quote="Close", start=start, end=end)
MMM <- get.hist.quote("MMM", quote="Close", start=start, end=end)
MNK <- get.hist.quote("MNK", quote="Close", start=start, end=end)
MNST <- get.hist.quote("MNST", quote="Close", start=start, end=end)
MO <- get.hist.quote("MO", quote="Close", start=start, end=end)  
MON <- get.hist.quote("MON", quote="Close", start=start, end=end)  
MOS <- get.hist.quote("MOS", quote="Close", start=start, end=end)  
MPC <- get.hist.quote("MPC", quote="Close", start=start, end=end) 
MRK <- get.hist.quote("MRK", quote="Close", start=start, end=end)  
MRO <- get.hist.quote("MRO", quote="Close", start=start, end=end)

Series <- zoo(cbind(MET, MHK, MJN, MKC, MLM, MMC, MMM, MNK, MNST, MO,
                    MON, MOS, MPC, MRK, MRO))
colnames(Series) <- c("MetLife", "Mohawk", "\nMead\nJohnson",
                      "McCormick", "Martin\nMarietta", 
                      "Marsh and\nMcLennan", "3M", "Mallinckrodt",  
                      "Monster\nBeverage", "Altria", "Monsanto", 
                      "The Mosaic\nCompany", "Marathon\nPetroleum",  
                      "Merck", "Marathon Oil")
Series <- na.approx(Series)

plot(Series, main = "", xlab = "")

为了呈现更好看的图表,我引入了命令\n 将y标签名称分成两行。但是图形输出将左边的 y 标签放在边距之外。

我尝试修改函数par() 中的mar 和mai,而我的所有输出都没有任何变化。我认为这可能与绘制的对象(动物园对象)相关联。

【问题讨论】:

    标签: r plot par


    【解决方案1】:

    tidyverse - 尤其是ggplot 可以更轻松地获得外观合理的图形,而无需无限地调整由三个字母缩写组成的参数:

    library(tidyverse)
    
    Series %>%
      as.data.frame %>%
      mutate(date = row.names(.) %>% as.Date) %>%
      gather(ticker, price, -date) %>%
      filter (!is.na(price)) ->
      dl
    
    dl %>%
      ggplot(aes(date, price)) +
      geom_line() +
      facet_wrap(~ticker, strip.position = "left", ncol = 2)
    

    注意:您甚至可以使用 facet_wrap(..., labeller = labeller(ticker = label_wrap_gen(10)) 自动包装 \n

    NB2:有些系列没有下载(都是NA),我没打扰

    【讨论】:

    • 我也在考虑ggplot2。但我更喜欢正常情节给出的输出。使用 ggplot 平滑所有系列以获得相同的 Y 比例。你能帮我修改上图的边距吗?
    • 听起来你需要facet_wrap(.., scales = "free_y") ;)。抱歉,我根本不知道/不知道 R 中的基本图形,但我怀疑 zoo 会有它自己的 plot 方法,它可以很高兴地忽略 par() 设置..
    • 经过一番谷歌搜索后,我找到了this,其中autoplot.zoo() 可能会更容易绘制您的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多