根据ggplot中的条件绘制rownames

时间:2018-03-16 12:23:37

标签: r ggplot2

我有这样的数据集:

df <- data.frame(v1 = rnorm(10), col = rbinom(10, size=1,prob= 0.5))
rownames(df) <- letters[1:10]

> head(df)
          v1 col
a -0.1806868   1
b  0.6934783   0
c -0.4658297   1
d  1.6760829   0
e -0.8475840   0
f -1.3499387   1

我这样画:

ggplot(df, aes(x = v1, y=rownames(df), group = col, color= col)) + geom_point()

enter image description here

现在我想只显示y轴上的col == 1的rownames。 不应显示其他名称(但应该是分数)

要添加一些上下文,我在y轴上有一个包含许多重叠变量名的图,但我只想显示虚线enter image description here之外的那些名称

2 个答案:

答案 0 :(得分:3)

您可以使用%zu

scale_y_discrete

enter image description here

答案 1 :(得分:2)

@MauritsEvers给出的答案没什么可补充的,我只是想到你的情节可能需要更少的水平线引导你的眼睛。

我们可以在breaks中使用scale_y_discrete参数。

set.seed(1); df <- data.frame(v1 = rnorm(10), col = rbinom(10, size=1,prob= 0.5))
rownames(df) <- letters[1:10]

axis_labels <- which(df$col == 1)
ggplot(df, aes(x = v1, y=rownames(df), group = col, color= col)) +
 geom_point() +
 scale_y_discrete(breaks = rownames(df)[axis_labels])

enter image description here