2017-11-16 1 views
0

어떻게 채우기 "이름"예를 변경할 수 있습니다 7 y 축에서 scale_x_discrete()를 사용하여 수정할 수 없습니다.ggplot 변경 테마 변경 geom_area는

누군가 도와주세요. 첨부

이미지이며, 아래의 코드

library(ggplot2) 

library(lubridate) 

theme_set(theme_bw()) 

df <- economics[, c("date", "psavert", "uempmed")] 

df <- df[lubridate::year(df$date) %in% c(1967:1981), ] 

# labels and breaks for X axis text 
brks <- df$date[seq(1, length(df$date), 12)] 

lbls <- lubridate::year(brks) 

# plot 
ggplot(df, aes(x=date)) + 

    geom_area(aes(y=psavert+uempmed, fill="psavert")) + 

    geom_area(aes(y=uempmed, fill="uempmed")) + 

    labs(title="Area Chart of Returns Percentage", 
      subtitle="From Wide Data format", 
      caption="Source: Economics", 
      y="Returns %") + # title and caption 

    scale_x_date(labels = lbls, breaks = brks) + # change to monthly ticks and 

labels 

    scale_fill_manual(name="", 
        values = c("psavert"="#00ba38", "uempmed"="#f8766d")) + # 
line color 

    theme(panel.grid.minor = element_blank()) + # turn off minor grid 

    annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns") #annotation layer 

enter image description here

답변

1

첫 번째 아래 예를 원래의 플롯 코드 같은 방법으로 할 수 있습니다에게 있습니다. 두 번째 방법은 데이터를 "긴"형식으로 변경하고 값의 이름을 다시 코딩하는 "ggplot-like"방식입니다.

library(tidyverse) 
library(lubridate) 

theme_set(theme_bw() + theme(panel.grid.minor=element_blank())) 

ggplot(df, aes(x=date)) + 
    geom_area(aes(y=psavert+uempmed, fill="Personal Saving Rate")) + 
    geom_area(aes(y=uempmed, fill="Unemployment Rate")) + 
    labs(title="Area Chart of Returns Percentage", 
     subtitle="From Wide Data format", 
     caption="Source: Economics", 
     y="Returns %") + # title and caption 
    scale_x_date(labels = lbls, breaks = brks) + # change to monthly ticks and labels 
    scale_fill_manual(name="", 
        values = c("Personal Saving Rate"="#00ba38", "Unemployment Rate"="#f8766d")) + # line color 
    scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) + 
    annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns") 

아래의 대안는 또한 플롯을 작성하기 전에 휴식 및 레이블 벡터를 만들 필요가 없습니다 scale_x_datedate_breaksdate_labels 인수를 사용합니다.

ggplot(df %>% gather(key, value, -date) %>% 
     mutate(key=recode(key, "psavert"="Personal Saving Rate", "uempmed"="Unemployment Rate")), 
     aes(x=date, y=value, fill=key)) + 
    geom_area() + 
    labs(title="Area Chart of Returns Percentage", 
     subtitle="From Wide Data format", 
     caption="Source: Economics", 
     y="Returns %", 
     fill="") + 
    scale_x_date(date_breaks="1 year", date_labels="%Y") + 
    scale_fill_manual(name="", values = c("#00ba38", "#f8766d")) + 
    scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) + 
    annotate("text", x=as.Date("1975-04-01"), 
      y=df %>% mutate(sum=psavert+uempmed) %>% pull(sum) %>% max + 1, 
      label="Year with highest returns")