gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:40:52 25 4
gpt4 key购买 nike

问。对于绘制的三个不同变量中的一个,我如何防止值 < 0 显示在 ggplot2 方面图中,每个变量都有不同的大小?

我制作了以下方面图。

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)

最佳答案

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

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')

关于R:如何有条件地更改 ggplot 构面图中使用的 3 个变量中的 1 个变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com