ggplot2在使用scale_x_sqrt时删除零

问题描述 投票:1回答:3

当我使用ggplot2绘制x坐标以零开始的数据并使用scale_x_sqrt选项时,绘图从x轴上的1开始而不是零。如果我添加limits=c(-0.1, 100),我会收到“NaNs产生”的错误。如何让ggplot2包含零?

r ggplot2
3个回答
2
投票

您可以通过平方根变换使轴下降到零,但不能低于零。转换产生x值低于零的虚数值。

library(tidyverse)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  scale_x_sqrt(limits=c(0,6), breaks=0:6, expand=c(0,0))

enter image description here


1
投票

我相信你正在寻找ggplot2中的expand_limits,如下所示:

library(ggplot2)
df <- data.frame(x = 1:10, y = 1:10)
g <- ggplot(df, aes(x, y)) + geom_point()
g <- g + expand_limits(x = 0, y = 0 )
g

enter image description here

?geom_expand

描述

有时,您可能希望确保限制包括单个值,适用于所有面板或所有图表。此函数是geom_blank周围的薄包装,可以轻松添加此类值。


0
投票

你可以在sqrt中使用aes

# Generate data
foo <- data.frame(a = 0:10, b = 1:11)
# Plot data
library(ggplot2)
ggplot(foo, aes(sqrt(a), b)) + 
    geom_point()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.