請幫助 :) 我使用 ggplot 在 R 上有以下堆積條形圖。
library (ggplot2)
library(ggthemes)
library(scales)
library(dplyr)
Sweets <- c("Smarties", "Smarties", "Jelly beans", "Jelly beans", "Jelly tots", "Jelly tots", "Astros", "Astros")
Sweet_Colour <- c("Blue","Red", "Blue","Red", "Blue","Red","Blue","Red")
Colour_Quantity <- c(13,14,25,36,96,85,9,12)
df <- data.frame(Sweets, Sweet_Colour, Colour_Quantity)
print (df)
pl <- ggplot(data = df, aes(x = Sweets, y= Colour_Quantity,fill = Sweet_Colour)) geom_bar(stat="identity", position = "fill") scale_y_continuous(labels = percent) ggthemes::theme_tufte() theme(axis.ticks.x= element_blank(),axis.text.x = element_text(angle = 90, hjust = 0), legend.position="top", text = element_text(size=20))
pl <- pl labs(x = "\n Sweet Type", y= "Percentage of Blue and Red Sweets \n ")
pl <- pl scale_fill_discrete(name = "")
pl
1
我想在堆疊圖上添加多少藍色和紅色糖果作為標簽。我嘗試使用 geom_text 將計數添加到圖表中,如下所示
pl <- pl geom_text(aes(label = Colour_Quantity), size = 3, position = position_stack(0.5))
但它改變了 y 軸上的比例,而圖形看起來像這樣。
2
請幫助我將顏色數量值添加到堆疊中,同時將 y 軸保持為百分比。
uj5u.com熱心網友回復:
向條形圖添加標簽時,始終使用與position條形相同的標簽,即切換到position_fillin geom_text:
library(ggplot2)
library(ggthemes)
library(scales)
library(dplyr)
pl <- ggplot(data = df, aes(x = Sweets, y = Colour_Quantity, fill = Sweet_Colour))
geom_bar(stat = "identity", position = "fill")
geom_text(aes(label = Colour_Quantity), size = 3, position = position_fill(vjust = .5))
scale_y_continuous(labels = percent)
ggthemes::theme_tufte()
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(angle = 90, hjust = 0),
legend.position = "top", text = element_text(size = 20))
pl <- pl labs(x = "\n Sweet Type", y = "Percentage of Blue and Red Sweets \n ")
pl <- pl scale_fill_discrete(name = "")
pl

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523490.html
標籤:rggplot2阴谋
上一篇:根據alpha值獲取顏色的名稱
