当我的数据中包含Inf值时,我正在尝试使用ggplotly进行barplot。
那是我的代码:
table<-data.frame("X"=c("a","b","c","d","e"),"Y"=c(-1,0,1,2,Inf))
p <- ggplot(table, aes(x=X, y=Y)) +
labs(x="X",y="Y") + geom_bar(stat="identity") + coord_flip() +
scale_x_discrete(limits = table$X[order(table$Y)])
p<-p+theme(
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(colour = "lightgray"),
plot.background = element_rect(fill="white")
)
p
ggplotly(p)
反正有解决办法吗?
谢谢
答案 0 :(得分:1)
ggplot在图的最大范围内显示无限值,而基数R plot
和plotly
则抛出非限定值。一种方法(唯一?)是操纵数据以将无限值转换为有限值,并调整expand
中的ggplot scale_y_continuous
项以匹配原始图。
How do ggplot and plot handle inf values differently?
table_max = max(table$Y[is.finite(table$Y)]) * 1.08 # Default ggplot padding beyond finite
# values; I thought 1.05 would work, but 1.08 empirically looks closer in this case
table2 <- table
table2$Y <- ifelse(table2$Y > table_max, table_max, table$Y)
p2 <- ggplot(table2, aes(x=X, y=Y)) +
labs(x="X",y="Y") + geom_bar(stat="identity") + coord_flip() +
scale_x_discrete(limits = table$X[order(table$Y)]) +
scale_y_continuous(expand = expand_scale(mult = c(0.05, 0)))
p2 <- p2+theme(
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(colour = "lightgray"),
plot.background = element_rect(fill="white")
)
p2
plotly::ggplotly(p2)