3

我有一个数据集,其中一组具有广泛的值。使用 ggplot 的 facet_wrap,我将以对数刻度绘制一组(具有最广泛值范围的组)的 y 轴和另一组的常规轴。

下面是一个可重现的例子。

set.seed(123)

FiveLetters <- LETTERS[1:2]

df <- data.frame(MonthlyCount = sample(1:10, 36, replace=TRUE),
CustName = factor(sample(FiveLetters,size=36, replace=TRUE)),
ServiceDate =  format(seq(ISOdate(2003,1,1), by='day', length=36), 
format='%Y-%m-%d'), stringsAsFactors = F)

df$ServiceDate <- as.Date(df$ServiceDate)

# replace some counts to really high numbers for group A

df$MonthlyCount[df$CustName =="A" & df$MonthlyCount >= 9 ] <-300

df

library(ggplot2)
library(scales)

ggplot(data = df, aes(x = ServiceDate, y = MonthlyCount))  +
geom_point() +  
facet_wrap(~ CustName, ncol = 1, scales = "free_y" ) +
scale_x_date("Date", 
               labels = date_format("%Y-%m-%d"), 
               breaks = date_breaks("1 week")) +
  theme(axis.text.x = element_text(colour = "black", 
                                   size = 16, 
                                   angle = 90, 
                                   vjust = .5))

结果图有两个方面。A 组的 facet 在图表的顶部和底部都有点,很难比较,B 的 facet 更容易阅读。我想以对数比例绘制 A 组的刻面,并让另一个“自由”。

4

2 回答 2

1

这可以完成工作

ggplot(data = df, aes(x = ServiceDate, y = MonthlyCount))  +
 geom_point() +  
 facet_wrap(~ CustName, ncol = 1, scales = "free_y" ) +
 scale_x_date("Date", 
           labels = date_format("%Y-%m-%d"), 
           breaks = date_breaks("1 week")) +
scale_y_continuous(trans=log_trans(), breaks=c(1,3,10,50,100,300),
                 labels = comma_format())+
 theme(axis.text.x = element_text(colour = "black", 
        size = 16, 
        angle = 90, 
        vjust = .5))
于 2015-11-19T20:09:41.310 回答
0

您可以进行转换后的每月计数并将其用作 y 轴。

## modify monthly count
df$mcount <- with(df, ifelse(CustName == "A", log(MonthlyCount), MonthlyCount))

ggplot(data = df, aes(x = ServiceDate, y = mcount))  +
  geom_point() +  
  facet_wrap(~ CustName, ncol = 1, scales = "free_y" ) +
  scale_x_date("Date", 
               labels = date_format("%Y-%m-%d"), 
               breaks = date_breaks("1 week")) +
  theme(axis.text.x = element_text(colour = "black", 
            size = 16, 
            angle = 90, 
            vjust = .5))

在此处输入图像描述

于 2015-07-20T16:22:03.080 回答