如何使用ggplots

时间:2017-08-25 14:32:03

标签: r ggplot2 boxplot

我有以下数据

head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

摘要统计信息:

data.frame':    153 obs. of  6 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R: int  190 118 149 313 NA NA 299 99 19 194 ...
 $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
 $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ...
 $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
 $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...

 name    type na       mean      disp median      mad  min   max nlevs
1   Ozone integer 37  42.129310 32.987885   31.5 25.94550  1.0 168.0     0
2 Solar.R integer  7 185.931507 90.058422  205.0 98.59290  7.0 334.0     0
3    Wind numeric  0   9.957516  3.523001    9.7  3.40998  1.7  20.7     0
4    Temp integer  0  77.882353  9.465270   79.0  8.89560 56.0  97.0     0
5   Month integer  0   6.993464  1.416522    7.0  1.48260  5.0   9.0     0
6     Day integer  0  15.803922  8.864520   16.0 11.86080  1.0  31.0     0

现在我想绘制连续变量的箱线图,我有以下代码,我正在使用其他数据集。

d <- melt(df)

p <- ggplot(d) + 
     geom_boxplot(aes(x=variable, y=value, color=variable,fill=variable))) +
     labs(x="", y="", title="Box Plot of Variables",subtitle="",caption="") + my_theme() + 
     scale_y_continuous(breaks=c(seq(0,100000,20000)), limits = c(0,100000)) +  
     theme(plot.title = element_text(lineheight=.8, face="bold",colour = "steelblue",hjust =0.5,vjust = 2,size = 11)) + 
     theme(text = element_text(size=10), axis.text.x = element_text(angle=45, hjust=1))

显然,scale_y_continuous()中的中断和限制参数必须针对此数据进行更改,这意味着每当我想绘制箱图时,必须每次都进行此操作;但这种方法并没有给我灵活性,使其具有可推广性。

说我希望它包含在我闪亮的应用程序中。

如何根据日期输入动态更改中断和限制参数,而不是每次都手动更改。

1 个答案:

答案 0 :(得分:1)

将此变量添加到您的代码中:

num.labels <- 10 #or whatever

然后将您对scale_y_continuous的通话更新为:

  scale_y_continuous(breaks= seq(min(d$value), max(d$value), length.out = num.labels),
                     limits = c(min(d$value),max(d$value))) 

你应该可以从那里拿走它。