在R中使用ggplot2制作新几何图形时,如何更改比例?
我想制作一个新的geom geom_spine():此geom与geom_bar()类似,但条形宽度根据计数而变化 这是我试过的在R中使用ggplot2制作新几何图形时,如何更改比例?,r,ggplot2,scale,geom-bar,R,Ggplot2,Scale,Geom Bar,我想制作一个新的geom geom_spine():此geom与geom_bar()类似,但条形宽度根据计数而变化 这是我试过的 require(ggplot2) "%||%" <- function(a, b) { if (!is.null(a)) a else b } geom_spine <- function(mapping = NULL, data = NULL, stat = "count", position
require(ggplot2)
"%||%" <- function(a, b) {
if (!is.null(a)) a else b
}
geom_spine <- function(mapping = NULL, data = NULL,
stat = "count", position = "fill",
color="black",size=0.2,
...,
width = NULL,
binwidth = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomSpine,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
width = width,
na.rm = na.rm,
color=color,
size=size,
...
)
)
}
colcount=function(data){
result=c()
myx=unique(data$x)
for(i in 1:length(myx)) result=c(result,sum(data[data$x==myx[i],"count"]))
result
}
GeomSpine <- ggproto("GeomSpine", GeomRect,
required_aes = c("x", "y"),
setup_data = function(data, params) {
data$width <- data$width %||%
params$width %||% (resolution(data$x, FALSE) * 0.9)
sumc<-c(0,colcount(data))
sumc<-cumsum(sumc)
total<-sum(data$y)/(length(unique(data$x))+1)
data1<-transform(data,
ymin = pmin(y, 0), ymax = pmax(y, 0),
xmin=sumc[x]+(sumc[x+1]-sumc[x])*(1-width)/2,xmax=sumc[x+1]-sumc[x+1]*(1-width)/2)
data<-transform(data1,
xmin=xmin/total,xmax=xmax/total,
x=(xmin+xmax)/(2*total), width=xmax-xmin
)
data
},
draw_panel = function(self, data, panel_scales, coord, width = NULL) {
ggproto_parent(GeomRect,self)$draw_panel(data, panel_scales, coord)
}
)
但是我想要的是:X轴的标签在杆的中间。
我无法解决这个问题。scale_x_continuous()函数的结果是
“错误:离散值提供给连续刻度”
在定义新几何图形时,如何将x轴更改为连续比例 您的映射当前具有x的离散变量(drv)。我想知道你是否应该定义一个新的统计数据并将结果映射到x,比如
.density..
或.count..
等等,在统计数据密度的情况下。换句话说,我不认为这是你在geom中可以做的事情。
ggplot(data=mpg,aes(x=drv,fill=factor(cyl)))+geom_spine()