簡體   English   中英

如何使用ggplot2而不是R中的默認圖繪制三點線

[英]How to plot three point lines using ggplot2 instead of the default plot in R

我有三個矩陣,我想使用ggplot2繪制圖形。 我有下面的數據。

library(cluster)
require(ggplot2)
require(scales)
require(reshape2)

data(ruspini)
x <- as.matrix(ruspini[-1])


w <- matrix(W[4,])

df <- melt(data.frame(max_Wmk, min_Wmk, w, my_time = 1:10), id.var = 'my_time')

ggplot(df, aes(colour = variable, x = my_time, y = value)) +
  geom_point(size = 3) +
  geom_line() +
  scale_y_continuous(labels = comma) +
  theme_minimal()

我想使用漂亮的ggplot2將這三個圖添加到一個圖中。 此外,我想使具有不同值的點具有不同的顏色。

我不太確定你在追求什么,這是一個猜測

您的數據...

max <- c(175523.9, 33026.97, 21823.36, 12607.78, 9577.648, 9474.148, 4553.296, 3876.221, 2646.405, 2295.504)
min <- c(175523.9, 33026.97, 13098.45, 5246.146, 3251.847, 2282.869, 1695.64, 1204.969, 852.1595, 653.7845)
w <- c(175523.947, 33026.971, 21823.364, 5246.146, 3354.839, 2767.610, 2748.689,   1593.822, 1101.469, 1850.013)

稍微修改您的基本繪圖代碼以使其工作...

plot(1:10,max,type='b',xlab='Number',ylab='groups',col=3)
points(1:10,min,type='b', col=2)
points(1:10,w,type='b',col=1)

這是你的意思嗎?

在此處輸入圖片說明

如果要使用ggplot2重現此ggplot2 ,則可以執行以下操作...

# ggplot likes a long table, rather than a wide one, so reshape the data, and add the 'time' variable explicitly (ie. my_time = 1:10)
require(reshape2)
df <- melt(data.frame(max, min, w, my_time = 1:10), id.var = 'my_time')

# now plot, with some minor customisations...
require(ggplot2); require(scales)
ggplot(df, aes(colour = variable, x = my_time, y = value)) +
  geom_point(size = 3) +
  geom_line() +
  scale_y_continuous(labels = comma) +
  theme_minimal()

在此處輸入圖片說明

編輯問題並更改示例數據后進行UPDATE ,這是適合新示例數據的編輯:

這是您的示例數據(此處存在簡化和提高速度的范圍,但這是另一個問題):

library(cluster)
require(ggplot2)
require(scales)
require(reshape2)

data(ruspini)
x <- as.matrix(ruspini[-1])

wss <- NULL
W=matrix(data=NA,ncol=10,nrow=100)

for(j in 1:100){
  k=10  
  for(i in 1: k){
    wss[i]=kmeans(x,i)$tot.withinss    
  }
  W[j,]=as.matrix(wss)
}

max_Wmk <- matrix(data=NA, nrow=1,ncol=10)

for(i in 1:10){
  max_Wmk[,i]=max(W[,i],na.rm=TRUE)
}

min_Wmk <- matrix(data=NA, nrow=1,ncol=10)
for(i in 1:10){
  min_Wmk[,i]=min(W[,i],na.rm=TRUE)
}

w <- matrix(W[4,])

這是將三個對象變成向量的操作,以便可以按預期制作數據幀:

max_Wmk <- as.numeric(max_Wmk)
min_Wmk <- as.numeric(min_Wmk)
w <- as.numeric(w)

現在像以前一樣重塑和繪圖...

df <- melt(data.frame(max_Wmk, min_Wmk, w, my_time = 1:10), id.var = 'my_time')

ggplot(df, aes(colour = variable, x = my_time, y = value)) +
  geom_point(size = 3) +
  geom_line() +
  scale_y_continuous(labels = comma) +
  theme_minimal()

結果如下:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM