使用多行y标签拟合绘图

时间:2017-04-07 14:40:51

标签: r plot par

我在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标签名称分成2行。但是图形输出会将左侧y标签放在边距之外。

R Plot Example

我试图在函数par()中修改mar和mai,而不会对我的所有输出进行任何更改。我认为这可能与绘制的对象(动物园对象)有关。

1 个答案:

答案 0 :(得分:0)

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)

tickers in ggplot

注意:您甚至可以使用\n

自动换行facet_wrap(..., labeller = labeller(ticker = label_wrap_gen(10)) NB2:部分系列没有下载(所有NAs),我没有打扰