问题
Here is a simplified and testable example:
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)
Error Description:
I can write this code
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)
and get this as output:
In order to ordenate months chronologically, I used sort
and 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")
The result was:
However, if I add margins = T
to facet_grid(. ~ sort(factor(MesDeConclusao, levels = month.name)),space = "free", scales="free", margins = T)
as I had in the previous example I get this error message:
Error in grid.Call.graphics(C_setviewport,vp,TRUE): non-finite location and/or size for viewport Calls: FUN -> push.vp.viewport -> grid.Call.graphics Execution halted
回答1:
I don't understand why sorting the factor levels inside the plot would be beneficial; this is best handled before plotting the data. The following seems to work just fine for me:
# 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)
来源:https://stackoverflow.com/questions/55855545/how-can-i-solve-non-finite-location-and-or-size-for-viewport-error