我想在ggplot中使用position_dodge和facet。问题是每个方面的比例不同,所以我需要为每个方面提供不同的position_dodge宽度。这可能吗?
由于我也想躲避geom_point(),因此无法自动计算此宽度。
library(data.table)
library(ggplot2)
data <- data.table(title= as.factor(c("car1", "car1", "car2", "car2", "car3") ),
scenario=as.factor(c("normal", "high", "normal", "high", "normal")),
price = c(1000,1000, 500,700,500),
doors= c(2,2,4, 4,2) )
data.long <- melt(data, id.vars=c("title", "scenario") )
data.long[,y_value :=value/mean(value), by= .(variable) ]
#can this be used in position_dodge?
data.long[, width_dodge:=(max(value)-min(value))/10, by=variable]
ggplot(data.long ,aes(x=value, y=y_value, shape=scenario, fill=title))+
geom_rect(aes(xmin=value-width_dodge,
xmax=value+width_dodge,
ymax=y_value , fill=title),
ymin=0, position=position_dodge() )+
scale_shape_manual(values=21:24)+
#can position_dodge(width ) be different per facet?
geom_point(aes(fill=title), colour="Black",position = position_dodge(width = 5) )+
facet_wrap(~variable, scales = "free_x")
答案 0 :(得分:0)
我使用通常的方法找到了一种解决方法:“计算外部ggplot”。可以早点考虑过这个......
library(data.table)
library(ggplot2)
data <- data.table(title= as.factor(c("car1", "car1", "car2", "car2", "car3") ),
scenario=as.factor(c("normal", "high", "normal", "high", "normal")),
price = c(1000,1000, 500,700,500),
doors= c(2,2,4, 4,2) )
data.long <- melt(data, id.vars=c("title", "scenario") )
data.long[,y_value :=value/mean(value), by= .(variable) ]
#this can be used in value_dodgedx
data.long[, width_dodge:=(max(value)-min(value))/10, by=variable]
data.long[,`:=`( I_group=1:.N,
N_group=.N,
group=.GRP,
#Here the actual dodging is done
value_dodgedx = value - ( (1:.N-0.5) - .N/2) *width_dodge ),
, by=.(variable, value, y_value)]
#providing x=value_dodgedx instead of x=value
ggplot(data.long ,aes(x=value_dodgedx, y=y_value, shape=scenario, fill=title ))+
geom_rect(aes(xmin=value_dodgedx-width_dodge/2,
xmax=value_dodgedx+width_dodge/2,
ymax=y_value , fill=title),
ymin=0, position=position_dodge() )+
scale_shape_manual(values=21:24)+
geom_point(colour="Black")+
facet_wrap(~variable, scales = "free_x")