ggplot 弄乱了 x 轴的数字顺序

ggplot is messing up x axis numerical order

我有一个看起来像这样的数据框:

基本上我想将 Y 与 X 绘制成一个配置文件,并根据 PROFILE_PREF_ID 和 INNER_FLAG 分隔线条和颜色。

出于非常神秘的原因,ggplot 决定更改我的 x 轴数值的顺序。我知道如果你有字符串或日期你可以使用因子,但在我的例子中它只是数值并且 ggplot 不应该弄乱这里的顺序。我读了很多关于 ggplot 弄乱 x 轴顺序的主题,并试图添加对 reorder() 函数的调用,但这根本没有进行绘图。

请在下面找到我的代码,其中重新排序功能不起作用。非常感谢任何建议。

g <- ggplot(dataset, aes(x=reorder(X, PK_ID), y=Y)) + 
geom_line(aes(color = as.character(PROFILE_PREF_ID), linetype = INNER_FLAG)) +
coord_fixed(ratio=1) +
theme_nothing()
g

轴通常运行从小到大的数字,如果你想翻转它可以使用scale_x_reverse。原始数据框的 x 值的顺序无关紧要。它们将根据它们在轴中的显示位置绘制。

dat=data.frame(x=c(99.187, 99.187, 99.164, 99.139, 99.069, 99.069, 98.458, 98.050),
           y=c(0, 1.579, 1.579, 99.164, 1.748, 1.748, 2.277, 2.974))
ggplot(dat) +
  geom_point(aes(x, y)) +
  scale_x_reverse()

您应该使用 geom_path 而不是 geom_line。示例:

library(ggplot2)

dat=data.frame(
x=c(0, 1, 1, 2, 1.8, 3),
y=c(0, 0, 2, 2, 1, 1))

ggplot(dat) +
  geom_line(aes(x, y))

ggplot(dat) +
  geom_path(aes(x, y))

康妮