大家晚上好
我的散點圖有問題,我將所有點放在 x 軸上的一個區域中,但我希望它分布在整個圖上。首先,這是我正在使用的一個最小示例:
data <- structure(list(names = structure(1:2, .Label = c("george", "harry"), class = "factor"),
gender = structure(c(1L, 1L), .Label = "male", class = "factor"),
data1 = c(0.373, 0.37), data2 = c(0.376, 0.377), data3 = c(0.371, 0.361),
data4 = c(0.3786, 0.3576), data5 = c(0.3262, 0.2928)), row.names = c(NA, -2L), class = "data.frame")
# names gender data1 data2 data3 data4 data5
# 1 george male 0.373 0.376 0.371 0.3786 0.3262
# 2 harry male 0.370 0.377 0.361 0.3576 0.2928
headers = c("data1","data2","data3","data4","data5")
names <- levels(unique(data$names))
bcol=as.factor(headers)
# colours
mapcol <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#0072B2", "#D55E00", "#CC79A7")
plot(
data[(data$gender == "male"),3],
col=mapcol[1],
pch=pch[20],
xlim=c(1,1800),ylim=c(0,1),
xlab="Names",ylab="Data Points",
axes=F,cex.lab=1.5
)
###### This is likely where the issue is:
for(i in seq_along(names) )
for(j in 3:7)
points(
data[(data$names == names[i]),j],
col=mapcol[j-3],pch=pch[bcol]
)
這是一個(經過編輯以洗掉任何機密資料)影像,顯示了此代碼(以及后來的一些僅用于繪制軸、圖例等的內容)的作用。

我的問題是,我希望資料分布在 x 軸上的每個名稱上,但目前都只顯示在“Harry”上。
uj5u.com熱心網友回復:
你的問題的根源是,你是給plot和points一次只單一值的情節。默認值會將您給出的y值解釋為一個值,并假設 x 值為 1。您可以通過提供x與名稱對應的值來解決此問題。
plot(
data[(data$gender == "male"),3],
col=mapcol[1],
## pch was not included in the question, so this arg caused an error
# pch=pch[20],
## key change: set the x limits to be 1 to the number of names
xlim=c(1,length(names)),
ylim=c(0,1),
xlab="Names",ylab="Data Points",
axes=F,cex.lab=1.5
)
for(i in seq_along(names)) {
for(j in 3:7) {
points(
i, ## use i as an x coordinate, making sure i starts at 1
data[(data$names == names[i]),j],
col=mapcol[j-3]
#,pch=pch[bcol]
## pch was not included in the question, so this argument caused an error
)
}
}

該points函式是矢量化的,因此我們還可以簡化您的代碼以消除其中一個回圈。這給出了相同的結果(盡管它確實假設資料框的排序順序與級別相同 - 如果您定義names <- unique(data$names),跳過冗余levels(),那么它將按照名稱出現在資料中的順序獲取名稱。
plot(
data[(data$gender == "male"),3],
col=mapcol[1],
## pch was not included in the question, so this arg caused an error
# pch=pch[20],
## key change: set the x limits to be 1 to the number of names
xlim=c(1,length(names)),
ylim=c(0,1),
xlab="Names",ylab="Data Points",
axes=F,cex.lab=1.5
)
for(j in 3:7) {
points(
x = seq_along(names),
y = data[, j],
col=mapcol[j-3]
)
}
uj5u.com熱心網友回復:
您可以嘗試使用data.table和ggplot2。第 1melt步:使用函式將資料框轉換為長格式第 2 步:使用 ggplot 繪制點
R代碼
library(data.table)
library(ggplot2)
data=as.data.table(data)
data_long=melt(data,id.vars=c("names","gender"),measure.vars=c("data1","data2","data3","data4","data5"))
ggplot(data=data_long,aes(x=names,y=values,col='variable'))
geom_point()


轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409143.html
標籤:
上一篇:使用R自適應地為ggplot文本(標題、副標題、標題等)開始一個換行符
下一篇:將資料幀直接轉換為列聯表(R)
