我正在嘗試使用 ggplot 繪制堆積條形圖。下面是我的代碼:
df = data.frame(Y = c(0,0,1,1), X = c(0,1,0,1), N = c(200, 50, 300, 70))
ggplot(data=df, aes(y=N, x= X, fill=Y))
geom_bar(position="stack", stat="identity", width=0.7)
scale_x_discrete(name ="", breaks = c(0, 1), labels=c("No",'Yes'))
theme(legend.position="none")
我想'No' and 'Yes'
在 x 軸上顯示為刻度標簽。但什么也沒有出現。有誰知道為什么我的刻度標簽沒有出現?我不明白我做錯了什么。
uj5u.com熱心網友回復:
您只需要插入factor(X)
以使 X 離散而不是連續:
library(tidyverse)
df <- data.frame(Y = c(0, 0, 1, 1), X = c(0, 1, 0, 1), N = c(200, 50, 300, 70))
ggplot(data = df, aes(y = N, x = factor(X), fill = Y))
geom_bar(position = "stack", stat = "identity", width = 0.7)
scale_x_discrete(name = "", breaks = c(0, 1), labels = c("No", "Yes"))
theme(legend.position = "none")
由reprex 包于 2022-06-14 創建(v2.0.1)
uj5u.com熱心網友回復:
一種更簡單的方法可能是在ggplot
函式之外進行資料轉換:
library(ggplot2)
library(dplyr)
df = data.frame(Y = c(0,0,1,1), X = c(0,1,0,1), N = c(200, 50, 300, 70))
df %>%
mutate(X = if_else(X == 0, "No", "Yes")) %>%
ggplot(aes(y=N, x= X, fill=Y))
geom_bar(position="stack", stat="identity", width=0.7)
theme(legend.position="none")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491033.html