2

问:如何防止在 ggplot2 构面图中仅显示三个不同变量之一的值 < 0,每个变量的大小都不同?

我制作了以下方面图。

在此处输入图像描述

如您所见,绘制在 y 轴上的值对于每个变量都存在显着差异,但使用scales = "free"可以解决该问题。

我想通过限制比例或将小于零的值设置为零来抑制“profit_margin”方面(底部为蓝色)中小于零的值,但我无法弄清楚如何实现这一点。我可以直接删除数据框中的值,但我更愿意保持数据不变。我尝试在 scale_y_continuous() 中使用一个函数,但无法取得任何进展。

这是用于生成上述图的代码:

require(lubridate)
require(reshape2)
require(ggplot2)
require(scales)

## Create dummy time series data
set.seed(12345)
monthsback <- 12
startdate <- as.Date(paste(year(now()),month(now()),"1",sep = "-")) - months(monthsback)
mydf <- data.frame(mydate = seq(as.Date(startdate), by = "month", length.out = monthsback),
                   sales = runif(monthsback, min = 600, max = 800),
                   profit = runif(monthsback, min = -50, max = 80))
## Add calculation based on data
mydf$profit_margin <- mydf$profit/mydf$sales

## Reshape...
mymelt <- melt(mydf, id = c('mydate'))

## Plot
p <- ggplot(data = mymelt, aes(x = mydate, y = value, fill = variable)) +
     geom_bar(stat = "identity") +
     facet_wrap( ~ variable, ncol = 1, scales = "free")

print(p)

这是我尝试使用函数并 lapply 将子零值设置为零:

require(lubridate)
require(reshape2)
require(ggplot2)
require(scales)

## Create dummy time series data
set.seed(12345)
monthsback <- 12
startdate <- as.Date(paste(year(now()),month(now()),"1",sep = "-")) - months(monthsback)
mydf <- data.frame(mydate = seq(as.Date(startdate), by = "month", length.out = monthsback),
                   sales = runif(monthsback, min = 600, max = 800),
                   profit = runif(monthsback, min = -50, max = 80))
## Add calculation based on data
mydf$profit_margin <- mydf$profit/mydf$sales

## Reshape...
mymelt <- melt(mydf, id = c('mydate'))

scales_function <- function(myvar, myvalue){
    mycount <- 1
    newval <- lapply(myvalue, function(myarg) {
        myarg <- ifelse(myvar[mycount] == "profit_margin", ifelse(myarg < 0, 0, myarg), myarg)
    }
                  )
    return(newval)
}

## Plot
p <- ggplot(data = mymelt, aes(x = mydate, y = value, fill = variable)) +
     geom_bar(stat = "identity") +
     facet_wrap( ~ variable, ncol = 1, scales = "free") +
     scale_y_continuous(breaks = scales_function(mymelt$variable, mymelt$value))

print(p)
4

1 回答 1

5

您可以保持数据不变,但只需绘制一个子集。

ggplot(data = subset(mymelt,!((variable == 'profit_margin') & value < 0)), 
       aes(x = mydate, y = value, fill = variable)) +
     geom_bar(stat = "identity") +
     facet_wrap( ~ variable, ncol = 1, scales = "free")

或在通话中更换

ggplot(data = mymelt, aes(x = mydate, y = replace(value, (variable == 'profit_margin') & value <0, NA), fill = variable)) +
 geom_bar(stat = "identity") +
 facet_wrap( ~ variable, ncol = 1, scales = "free") +
 ylab('value')
于 2012-05-30T02:24:36.270 回答