[英]Add text labels to a ggplot2 mosaic plot
使用以下數據:
Category <- c("Bankpass", "Bankpass", "Bankpass", "Moving", "Moving")
Subcategory <- c("Stolen", "Lost", "Login", "Address", "New contract")
Weight <- c(10,20,13,40,20)
Duration <- as.character(c(0.2,0.4,0.5,0.44,0.66))
Silence <- as.character(c(0.1,0.3,0.25,0.74,0.26))
df <- data.frame(Category, Subcategory, Weight, Duration, Silence)
我用它來創建以下馬賽克圖:
library (ggplot2)
library (ggmosaic)
g <- ggplot(data = df) +
geom_mosaic(aes(weight = Weight, x = product(Category), fill = Duration),
offset = 0, na.rm = TRUE) +
theme(axis.text.x = element_text(angle = -25, hjust = .1)) +
theme(axis.title.x = element_blank()) +
scale_fill_manual(values = c("#e8f5e9", "#c8e6c9", "#a5d6a7", "#81c784", "#66bb6a"))
這是有效的,但我想在圖表上的元素上包含文字標簽(“顯示fe被盜,丟失”等)
但是,當我這樣做時:
g + geom_text(x = Category, y = Subcategory, label = Weight)
我收到以下錯誤:
UseMethod中的錯誤(“rescale”):沒有適用於“rescale”的方法應用於類“character”的對象
對這里出了什么問題的想法?
這是我的嘗試。 x軸是離散變量(即,類別)。 所以你不能在geom_text()
使用它。 你不知何故需要為軸創建一個數字變量。 同樣,您需要在y軸上找到標簽的位置。 為了獲得兩個維度的數值,我決定訪問保留在圖形后面的數據框。 當您使用ggmosaic
包時,在這種情況下,圖形后面有一個數據框。 你可以使用ggplot_build()
來獲取它。 您可以使用數據框中的信息(例如,xmin和xmax)計算x和y值。 這是個好消息。 但是,我們也有壞消息。 當您到達數據時,您意識到標簽不需要有關子類別的信息。
我們可以克服這一挑戰,將上述數據框與原始數據相結合。 當我加入數據時,我計算了原始數據和其他數據的比例。 這些值有意轉換為字符。 temp
是添加標簽所需的數據集。
library(dplyr)
library(ggplot2)
library(ggmosaic)
# Add proportion for each and convert to character for join
df <- group_by(df, Category) %>%
mutate(prop = as.character(round(Weight / sum(Weight),3)))
# Add proportion for each and convert to character.
# Get x and y values for positions
# Use prop for join
temp <- ggplot_build(g)$data %>%
as.data.frame %>%
transmute(prop = as.character(round(ymax - ymin, 3)),
x.position = (xmax + xmin) / 2,
y.position = (ymax + ymin) / 2) %>%
right_join(df)
g + geom_text(x = temp$x.position, y = temp$y.position, label = temp$Subcategory)
我想你正在尋找這樣的東西
library(ggplot2)
library(ggmosaic)
你的數據:
Category <- c("Bankpass", "Bankpass", "Bankpass", "Moving", "Moving")
Subcategory <- c("Stolen", "Lost", "Login", "Address", "New contract")
Weight <- c(10,20,13,40,20)
Duration <- as.character(c(0.2,0.4,0.5,0.44,0.66))
Silence <- as.character(c(0.1,0.3,0.25,0.74,0.26))
mydf <- data.frame(Category, Subcategory, Weight, Duration, Silence)
ggplot(data = mydf) +
geom_mosaic(aes( x = product(Duration, Subcategory), fill=factor(Duration)), na.rm=TRUE) +
theme(axis.text.x=element_text(angle=-25, hjust= .1)) +
labs(x="Subcategory", title='f(Duration, Subcategory | Category)') +
facet_grid(Category~.) +
guides(fill=guide_legend(title = "Duration", reverse = TRUE))
輸出是:
它幾乎是你在ggmosaic
包上做的最好的。 你應該嘗試其他包。
祝你的項目工作順利;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.