我嘗試在以下條件下添加多行標題:第一行應居中,所有下一行都必須向左對齊。我嘗試了以下代碼,但標題看起來不像我計劃的那樣,如下圖所示。

有什么方法可以改進我的代碼以按照我的意圖呈現標題?
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))
geom_point()
geom_line()
ylab("HHI")
labs(caption=expression(paste(italic("Source:"),"By author's calculation \n Two extreme cases would have \n something blabla equal to 10,000 and 0, respectively.")))
uj5u.com熱心網友回復:
我認為當您分別為標題的每個部分使用自定義注釋時,您會獲得最好的(并且最不會頭疼)。事實上,這種型別的解決方案有助于解決很多很多問題——我想我至少在 50% 的答案中建議了這一點,這些答案只是看似非常不同的問題......:D
代碼中的更多注釋。
library(ggplot2)
## I am typically defining x and y outside of ggplot in order to keep the code clearer -
## x and y position very strongly depend on your final plot dimensions
## and you will need to fine tune them depending on those
## the below is a semi-automatic approach
x_cap = mean(range(iris$Sepal.Length))
y_cap = min(iris$Sepal.Width)- .2*mean(range(iris$Sepal.Width ))
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))
geom_point()
geom_line()
## I prefer annotating with annotate, if its only a single element
annotate(geom = "text", x = x_cap, y = y_cap,
label = as.character(expression(paste(italic("Source:"),"By author's calculation"))),
hjust = .5, parse = TRUE)
annotate(geom = "text", x = -Inf, y = y_cap-.2*y_cap,
label = "Two extreme cases would have \n something blabla equal to 10,000 and 0, respectively.",
hjust = 0)
## you need then to change your limits, and turn clipping off
coord_cartesian(ylim = range(iris$Sepal.Width), clip = "off")
labs(y = "HHI")
## you also need to adjust the plot margins
theme(plot.margin = margin(.1, .1, 1, .1, unit = "inch"))

由reprex 包(v2.0.1)于 2021 年 11 月 25 日創建
uj5u.com熱心網友回復:
這只是作為參考:實作您想要的結果的第二個選擇是通過patchwork包,它是我幾乎所有東西annotation_custom的首選(就像@tjebo 一樣)。基本上,我通過一個“空白”標題圖添加標題的第二部分,我將其粘貼到主圖上:
library(patchwork)
library(ggplot2)
p <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))
geom_point()
geom_line()
ylab("HHI")
theme(plot.caption = ggtext::element_markdown(hjust = .5),
plot.margin = margin(5.5, 5.5, 0, 5.5, "pt"))
labs(caption = "*Source:* By author's calculation")
p_caption <- ggplot(iris)
geom_blank()
theme_void()
theme(plot.caption = element_text(hjust = 0, margin = margin(0, 0, 0, 0, "pt")),
plot.margin = margin(0, 5.5, 5.5, 5.5, "pt"))
labs(caption = paste("Two extreme cases (monopoly and perfectly competitive market) would have",
"an HHI equal to 10,000 and 0, respectively.",
"This figure shows that the market is not monopoly.", sep = "\n"))
p / p_caption plot_layout(heights = c(40, 1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366451.html
