解決策 1 : 元の試みに固執したい場合は、車の名前の適切な y 座標を計算し、それを別のデータ ソースとして追加します。この geom_text レイヤーが以下を使用inherit.aes = FALSE
して作成された ggplot オブジェクトから何も継承しないように使用しggparcoord()
ます。
library(dplyr)
p1 <- ggparcoord(mtcars,
columns = c(12, 1, 6),
groupColumn = 1) +
geom_text(data = mtcars %>%
select(carName) %>%
mutate(x = 1,
y = scale(as.integer(factor(carName)))),
aes(x = x, y = y, label = carName),
hjust = 1.1,
inherit.aes = FALSE) +
# optional: remove "carName" from x-axis labels
scale_x_discrete(labels = function(x) c("", x[-1])) +
# also optional: hide legend, which doesn't really seem relevant here
theme(legend.position = "none")
p1

解決策 2 : この代替手段では、グループ列として carName を使用し、それを平行座標列の 1 つとして渡しません。(これは、この関数が意図するユースケースにより近いと思います...) group 列として carName を指定すると、この時点でdata
作成された ggplot オブジェクトのスロットに車の名前の値を取り込むことができるため、ラベルがそれを直接継承し、対応する行(または実際のユースケースでは、最初の平行座標列の名前が何であれ)のみをフィルタリングします。y 座標は上記のように均等に分散されていませんが、ggrepel パッケージからは、重なっているテキスト ラベルを互いにずらすのに適切な仕事をします。ggparcoord()
geom_text
variable == "mpg"
geom_text_repel
library(dplyr)
library(ggrepel)
p2 <- ggparcoord(mtcars,
columns = c(1, 6),
groupColumn = "carName") +
geom_text_repel(data = . %>%
filter(variable == "mpg"),
aes(x = variable, y = value, label = carName),
xlim = c(NA, 1)) + # limit repel region to the left of the 1st column
theme(legend.position = "none") # as before, hide legend since the labels
# are already in the plot
p2

解決策 3 / 4ggplot()
:舞台裏で予期しないことを行う可能性のある拡張機能に依存することなく、実際に同じことを でプロットできます。
library(dplyr)
library(tidyr)
library(ggrepel)
# similar output to solution 1
p3 <- mtcars %>%
select(carName, mpg, wt) %>%
mutate(carName.column = as.integer(factor(carName))) %>%
gather(variable, value, -carName) %>%
group_by(variable) %>%
mutate(value = scale(value)) %>%
ungroup() %>%
ggplot(aes(x = variable, y = value, label = carName, group = carName)) +
geom_line() +
geom_text(data = . %>% filter(variable == "carName.column"),
hjust = 1.1) +
scale_x_discrete(labels = function(x) c("", x[-1]))
p3
# similar output to solution 2
p4 <- mtcars %>%
select(carName, mpg, wt) %>%
gather(variable, value, -carName) %>%
group_by(variable) %>%
mutate(value = scale(value)) %>%
ungroup() %>%
ggplot(aes(x = variable, y = value, label = carName, group = carName)) +
geom_line() +
geom_text_repel(data = . %>% filter(variable == "mpg"),
xlim = c(NA, 1))
p4

編集
上記のそれぞれについて、右側にもテキスト ラベルを追加できます。wt
ラベルはのスケーリングされた値に従って配置されるため、ラベルの位置がうまく配置されない場合があることに注意してください。
p1 +
geom_text(data = mtcars %>%
select(carName, wt) %>%
mutate(x = 3,
y = scale(wt)),
aes(x = x, y = y, label = carName),
hjust = -0.1,
inherit.aes = FALSE)
p2 +
geom_text_repel(data = . %>%
filter(variable == "wt"),
aes(x = variable, y = value, label = carName),
xlim = c(2, NA))
p3 +
geom_text(data = . %>% filter(variable == "wt"),
hjust = -0.1)
p4 +
geom_text_repel(data = . %>% filter(variable == "wt"),
xlim = c(2, NA))
