这是一个简化且可测试的示例:
dataset <- data.frame(
emp_month = c("January","March","April","May","December"),
salary = c(623.3,515.2,611.0,729.0,843.25))
library(ggplot2)
ggplot(dataset)+
geom_boxplot(aes(x = sort(factor(emp_month)), y = salary))+
geom_point(aes( x = sort(factor(emp_month)), y=salary))+
facet_grid(. ~ sort(factor(emp_month)),space = "free", scales="free",margins = T)
错误说明:
我可以编写这段代码
library(ggplot2)
MesDeConclusao = factor(MesDeConclusao, levels = month.name)
MesDeConclusao = sort(MesDeConclusao)
ggplot(dataset)+
geom_boxplot(aes(x = MesDeConclusao, y = Horas.Totais.PE))+
geom_point(aes( x = MesDeConclusao, y=Horas.Totais.PE))+
facet_grid(. ~ MesDeConclusao,space = "free", scales="free",margins = T)
并将其作为输出:
为了按时间顺序排列数月,我使用了sort
和facto
r:
library(ggplot2)
MesDeConclusao = factor(MesDeConclusao, levels = month.name)
MesDeConclusao = sort(MesDeConclusao)
ggplot(dataset)+
geom_boxplot(aes(x = sort(factor(MesDeConclusao, levels = month.name)), y = Horas.Totais.PE))+
geom_point(aes( x = sort(factor(MesDeConclusao, levels = month.name)), y=Horas.Totais.PE))+
facet_grid(. ~ sort(factor(MesDeConclusao, levels = month.name)),space = "free", scales="free")
结果是:
但是,如果像在上一个示例中一样,将margins = T
添加到facet_grid(. ~ sort(factor(MesDeConclusao, levels = month.name)),space = "free", scales="free", margins = T)
,则会收到此错误消息:
grid.Call.graphics(C_setviewport,vp,TRUE)中的错误: 视口的位置和/或大小不受限制 调用:FUN-> push.vp.viewport-> grid.Call.graphics 执行停止
答案 0 :(得分:2)
我不明白为什么对图中的因子水平进行排序会有所帮助;最好在绘制数据之前进行处理。以下似乎对我来说很好:
# Just to ensure levels are in correct order
dataset$emp_month <- factor(
dataset$emp_month,
levels = c("January", "March", "April", "May", "December")
)
ggplot(dataset) +
geom_boxplot(aes(x = emp_month, y = salary)) +
geom_point(aes(x = emp_month, y = salary)) +
facet_grid(. ~ emp_month ,space = "free", scales = "free", margins = T)