2015-11-13 61 views
4

我想用ggplot來繪製一個顯示yaxis百分比的圖。 這裏的數據和代碼,我用ggplot百分比乘以100

data<-"yrs.1.17 yrs.18.44 yrs.45.64 yrs.65.84 yrs.85. 
1  4.53  35.12  32.93  22.86 4.57 
2  4.01  34.74  34.19  22.71 4.34 
3  4.75  33.23  35.19  22.28 4.51 
4  4.60  34.04  36.93  20.70 3.56 
5  4.80  33.82  37.69  19.97 3.52 
6  4.30  35.09  37.08  19.83 3.65 
7  3.65  38.08  36.19  19.18 2.85 
8  3.72  38.11  36.10  19.22 2.86" 

mydata<- read.table(text=data, header=TRUE) 


year<-c(2006,2007,2008,2009,2010,2011,2012,2013) 
df<-data.frame(year,mydata) 
library(ggplot2) 
library(reshape2) 
library(scales) 
newdf<-melt(df,'year') 
ggplot(newdf,aes(x=year,y=value,group=variable,color=variable))+ geom_line(size=1)+ 
scale_x_continuous(breaks=year)+xlab("Year")+scale_y_continuous(labels = percent,limits=c(1,50),breaks=seq(5,50,by=5))+ylab("Age groups")+ 
geom_point(aes(shape=variable),size=3)+ 
ggtitle("Age groups of people between 2006 and 2013")+ 
theme(legend.title=element_blank(), legend.justification=c(0.6,0.6), legend.position=c(0.95,0.95), legend.text = element_text(size=9), 
axis.text = element_text(size=9), axis.title = element_text(size=9), plot.title=element_text(size = 9))  

正如你可以在輸出的百分比都乘以100看是否有一種方式來獲得正確的百分比。
非常感謝。

+0

我已經嘗試在代碼中使用以下代碼,但沒有任何更改。 scale_y_continuous(labels = percent) scale_y_continuous(labels = scales :: percent) scale_y_continuous(labels = percent_format()) – paulvr

+0

第一個問題的好例子(plus1)。如果Gregor回答了您的問題,您可以通過點擊旁邊的勾號來標記它(您也可以點擊。 – user20650

回答

2

只是除以100:

ggplot(newdf, 
    aes(
    x = year, 
    y = value/100, # here divide by 100 
    group = variable, 
    color = variable 
) 
) + 
    geom_line(size=1)+ 
    scale_x_continuous(breaks=year) + 
    xlab("Year") + 
    scale_y_continuous(
    labels = percent, 
    limits = c(.01, .5),   # here divide by 100 
    breaks = seq(.05, .5, by = .05) # here divide by 100 
) + 
    ylab("Age groups") + 
    geom_point(aes(shape = variable), size=3) + 
    ggtitle("Age groups of people between 2006 and 2013") + 
    theme(legend.title=element_blank(), 
     legend.justification = c(0.6, 0.6), 
     legend.position = c(0.95, 0.95), 
     legend.text = element_text(size = 9), 
     axis.text = element_text(size = 9), 
     axis.title = element_text(size = 9), 
     plot.title = element_text(size = 9)) 

作爲一個側面說明,而不是element_text(size = 9)所有的手動設置,多數主題採取base_size參數,所以使用theme_grey(9)theme_classic(9)會做的大部分工作,爲您。您可能仍然需要調整標題。

+0

完美,謝謝。 – paulvr