R:如何有条件地更改ggplot facet图中使用的3个变量的值

时间:2012-05-30 02:12:33

标签: r ggplot2

Q值。我怎样才能防止值< 0在ggplot2 facet图中显示,只绘制了三个不同变量中的一个,每个变量的幅度各不相同?

我做了以下方面的情节。

enter image description here

如您所见,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)

1 个答案:

答案 0 :(得分: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')