我有問題。我的 ggplot 不斷將兩個同名的向量合并為一個,我希望將它作為兩個單獨的條,分別標記為 QVAR REDIHALER 和其他標簽。
data.frame(
brand_name = c("QVAR REDIHALER", "QVAR REDIHALER", "XARELTO", "XIFAXAN", "LATUDA", "TRINTELLIX", "VYVANSE", "NUCYNTA"),
n = c(78, 48, 71, 26, 8, 5, 8, 1))
brand_name1 %>%
ggplot(mapping = aes(x = reorder(brand_name, (-n)), y = n, fill = brand_name))
geom_bar(stat = "identity", position = "dodge", )
geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1)
theme_bw()
theme(axis.text.x = element_text(angle = 45, hjust = 1))
theme(plot.title = element_text(face = "bold"),
axis.text.y = element_text(size = 14, colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank())
ylab("Count")
xlab("")
labs(fill = "Brand name", title = "Top Rebate Eligable - Brand")
scale_fill_brewer(palette = "Set2")
coord_flip()
問題是箭頭指向的地方。我想讓“QVAR REDIHALER”在資料框中重復兩次,而不是折疊到一個欄

uj5u.com熱心網友回復:
不確定如何將重復的類別分成兩列。但我試一試。
一種選擇是通過使用輔助列使重復的類別唯一,例如將數字 1、2、... 添加到每個類別并將此幫助列映射到y. 這樣做你會得到單獨的列。要擺脫軸標簽上顯示的數字,您可以通過 使用貼標機功能scale_y_discrete,即使用例如gsub洗掉數字:
library(ggplot2)
library(dplyr)
brand_name1 <- brand_name1 %>%
group_by(brand_name) %>%
mutate(brand_name_uniq = paste0(brand_name, row_number()))
ggplot(brand_name1, mapping = aes(x = reorder(brand_name_uniq, (-n)), y = n, fill = brand_name))
geom_bar(stat = "identity", position = "dodge", )
geom_text(aes(label = n), position = position_dodge(width = 0.9), hjust = -1)
scale_x_discrete(labels = ~gsub("\\d$", "", .x))
theme_bw()
theme(axis.text.x = element_text(angle = 45, hjust = 1))
theme(plot.title = element_text(face = "bold"),
axis.text.y = element_text(size = 14, colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank())
ylab("Count")
xlab("")
labs(fill = "Brand name", title = "Top Rebate Eligable - Brand")
scale_fill_brewer(palette = "Set2")
coord_flip()

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