我剛從 R 視覺效果開始,我被困在這個上。在下面的代碼中,您將找到我正在使用的表格及其渲染。
我想要做的是獲得一個水平條形圖,其中對于每個池值我有兩個變數(D_MTD 和 I_MTD)。
為了實作這一點(我不知道這是否是正確的做法)我添加了兩個 geom_bar 層,我得到的幾乎就是它應該看起來的樣子(可以有堆疊的列)。
MyTable <- data.frame(
Pool = c(" ", "(CA) Domestic", "(CA) International", "(FR) International", "(US) Domestic", "(US) International" ),
ADomestic = c(0, 36000, 3000, 1200, 54000, 6000),
AInternational = c(0, 0, 600, 600, 0, 1200),
D_MTD = c(23.4, 0, 0, 0, 8.38, 0),
I_MTD = c(6.63, 0, 0, 0, 0, 0)
)
MyTable
MyVisual <- MyTable %>%
ggplot(
Data = MyTable,
aes(y = Pool)
)
geom_bar(
aes(
weight = D_MTD,
colour = "Domestic"
),
alpha = 0.5
)
geom_bar(
aes(
weight = I_MTD,
colour = "International"
),
alpha = 0.5
)
labs(
title = "Month-To-Date Consumption by Pool",
subtitle = "(in minutes)",
y = "Pools",
x = "MTD Used Minutes",
colour = "Pool context"
)
MyVisual

但是,視覺有兩種我不想要的輪廓顏色(我希望條形圖改為填充顏色)。我嘗試使用填充引數為條形分配固定顏色(例如:紅色代表國內,藍色代表國際),但這會生成另一個我不想顯示的圖例。
例子:
MyVisual <- MyTable %>%
ggplot(
Data = MyTable,
aes(y = Pool)
)
geom_bar(
aes(
weight = D_MTD,
colour = "Domestic",
fill = "red"
),
alpha = 0.5
)
geom_bar(
aes(
weight = I_MTD,
colour = "International",
fill = "blue"
),
alpha = 0.5
)
labs(
title = "Month-To-Date Consumption by Pool",
subtitle = "(in minutes)",
y = "Pools",
x = "MTD Used Minutes",
colour = "Pool context"
)
MyVisual

另外,如何將標簽應用于具有相應值的每個條?
提前致謝!
uj5u.com熱心網友回復:
該解決方案應該適合您。它包含的元素和轉換對于初學者來說可能會令人困惑,但在某些時候你將不得不面對這些。我建議你閱讀 R for Data Science 這本書,至少是與 ggplot2 進行資料可視化相關的章節。
腳步:
1- 使用函式重塑資料pivot_longer()2- 為繪圖創建因子和標簽
library(tidyr)
library(dplyr)
library(ggplot2)
MyTable <- data.frame(
Pool = c(" ", "(CA) Domestic", "(CA) International", "(FR) International", "(US) Domestic", "(US) International" ),
ADomestic = c(0, 36000, 3000, 1200, 54000, 6000),
AInternational = c(0, 0, 600, 600, 0, 1200),
D_MTD = c(23.4, 0, 0, 0, 8.38, 0),
I_MTD = c(6.63, 0, 0, 0, 0, 0)
)
to_plot <- MyTable %>%
select(Pool, D_MTD, I_MTD) %>%
# Data to long format
pivot_longer(
cols = contains('MTD'),
names_to = 'pool_context',
values_to = 'used_minutes'
) %>%
mutate(
pool_context = factor(
pool_context, c('D_MTD', 'I_MTD'), c('Domestic', 'International')
),
# Labels only for non 0 values
label = ifelse(used_minutes == 0, NA, used_minutes)
)
to_plot %>%
ggplot(aes(y = Pool, x = used_minutes))
# Fill aesthetic only for bars, to avoid labels to get color too
geom_col(aes(fill = pool_context))
theme(legend.position = 'bottom')
geom_label(aes(label = label), hjust = 1.1)
labs(fill = NULL, x = 'Used minutes (MTD)', y = 'Pool')

由reprex 包于 2022-02-17 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426667.html
上一篇:如何將此資料繪制為折線圖?
下一篇:根據具有相似名稱的其他列改變變數
