由於沒有以正確的格式存儲數據集,因此出現此錯誤。有了你的數據,你有一個t
變量和g
變量。 ggplot
想要接收描述該軸/特徵的所有元素的aes值。
您擁有的數據是寬格式(多列)。 ggplot2
更好地利用長格式數據(鍵值對)。要將寬數據轉換爲長數據,請使用tidyr
包(具體爲gather
函數)將值收集到一列變量和一列值中。在你的情況下,變量是g和t,值是你的百分比。
然後,您會將轉換的數據傳遞到ggplot
,指定x軸爲變量,y軸爲百分比。您想將它繪製爲條形碼,geom_bar()
設置爲stat = "identity"
,因爲您正在提供值。最後一步是通過scale_y_continuous
將y軸上的標籤設置爲百分比。
library(tidyr)
library(ggplot2)
library(scales)
df <- data.frame(g = 0.936871,
t = 0.063129)
df <- gather(df, variable, value)
ggplot(df, aes(x = variable, y = value)) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = percent)
結果看起來是這樣的:
至於您的評論的請求:
df <- data.frame(
category = c(1, 2),
g = c(0.8070175, 0.97099768),
t = c(0.1929825, 0.029000232)
)
df <- gather(df, variable, value, -category)
ggplot(df, aes(x = category, y = value)) +
geom_col(aes(fill = variable), position = position_dodge()) +
scale_y_continuous(labels = percent) +
scale_x_discrete(limits = c(1,2), breaks = c(1,2), labels = c("Category 1", "Category 2"))
嘗試張貼產生錯誤的代碼:HTTPS: //stackoverflow.com/help/mcve –