我answering這個question,我遇到一個奇怪的問題;錯誤軸標籤ggplot小格
我想用ggplot2
製作條形圖,並將x軸標籤作爲Group
列的最後一個字符。使用substring(Group, 3, 3)
爲了這個目的:
substring(df$Group, 3, 3)
# [1] "1" "2" "3" "1" "2" "1" "2" "3" "4"
但是,當我在ggplot
下面一樣使用它,它打印1
,而不是4
在最後一跳;
ggplot(data=df, aes(x=Group, y=Value)) +
geom_bar(stat="identity") +
scale_x_discrete(labels = substring(Group, 3, 3), expand=c(0.1,0.1)) +
facet_grid(~ substring(Group, 1, 1), space="free_x", scales="free_x", switch="x") +
theme_bw() +
theme(strip.placement = "outside",
strip.background = element_rect(fill=NA,colour="grey50"),
panel.spacing=unit(0,"cm"))
我可以得到它通過使用labels =unique(substring(Group, 3, 3)
工作,但會有人解釋這是怎麼回事?
數據:
df <- structure(list(Group = structure(1:9, .Label = c("1_1", "1_2",
"1_3", "2_1", "2_2", "3_1", "3_2", "3_3", "3_4"), class = "factor"),
Value = c(-1.23, 2.34, 0.56, 1.87, -2.4, 5.54, -0.98, -2.31,
6)), .Names = c("Group", "Value"), row.names = c(NA, -9L), class = "data.frame")
# > df
# Group Value
# 1 1_1 -1.23
# 2 1_2 2.34
# 3 1_3 0.56
# 4 2_1 1.87
# 5 2_2 -2.40
# 6 3_1 5.54
# 7 3_2 -0.98
# 8 3_3 -2.31
# 9 3_4 6.00
如果我用什麼'$ DF Group'?我試過這個,仍然得到相同的結果。除此之外,我甚至使用了'labels = c(「1」,「2」,「3」,「1」,「2」,「1」,「2」,「3」,「4」)'我再次得到同樣的情節? o.O很奇怪,不是嗎? – Masoud
您有一個具有4個不同值的軸,並且您提供了9個標籤。它使用您提供的前四個標籤。什麼是令人驚訝的? – Gregor
可能是一個天真的問題,但爲什麼我有4個不同的值? – Masoud