2016-09-22 28 views
1

我有有像下面數據的大型數據集:如何繪製R中一個曲線圖,是不是箱和晶須情節

 Age   Ethnicity   Gender  Crude_Rate 
     20-24  Pacific Islander Female  39.2 
     55-59  Caucasian   Male   100.3 
     60-64  African   Female  3.2 
     30-34  Asian    Male   2.8 

我試圖R上的畫三個地塊:

  • 粗率(y軸總是)對年齡
  • 針對種族粗率
  • 針對性別粗率

我得到情節,但它是一個盒子和晶須的情節與上面的點,這不是我想要的。我只想將點繪製成散點圖。

我使用的代碼是:

melanoma <-read.csv("Melanoma Age.csv", header=TRUE, na.strings = c("Not  Applicable")) 
melanoma<-na.omit(melanoma) 


plot(melanoma$Gender, melanoma$Crude_Rate,las=2, ylab="Crude Rate", xlab="Gender", main="Crude Rates for Both Genders") 
plot(melanoma$Age, melanoma$Crude_Rate,las=2, ylab="Crude Rate", main="Crude Rates for Different Age Groups") 
plot(melanoma$Ethnicity, melanoma$Crude_Rate,las=2, ylab="Crude Rate", main="Crude Rates for Different Ethnicities") 

我不明白我做了什麼錯的,因爲通常我這樣做的時候,我得到的散點圖,而不是一個箱須圖以點它上面。

謝謝你在先進的任何幫助

+0

當y是一個因子時,R傾向於繪製箱形圖。如果您需要散點圖,請嘗試繪製沒有y軸的圖形,但指定不同的顏色或點形狀,即使用像「plot(黑素瘤$ Crude_Rate,col =黑色素瘤$ Gender,...)這樣的smth」,其中......代表任何其他陰謀參數。另一個建議是使用數據的子集並將它們繪製在不同的圖表上。 –

+0

@德米特里格雷科夫謝謝你,我試圖陰謀(黑色素$ Crude_Rate,col =黑色素瘤$性別),現在我得到一個散點圖,但不幸的是x軸標籤是數字不是女性和男性。 – glh

+0

veritcal軸現在用於Crude_Rate,而水平標籤只是觀察的索引。你可以使用'legend()'來指定哪個性別用某種顏色繪製。 –

回答

0

您還可以使用汽車包和功能散點圖。這將爲您提供額外的圖表(例如盒子和鬍鬚,更平滑),但這些可以很容易地刪除。

+0

謝謝你 – glh

0

如果你的x值是一個因子變量,你就可以生產散點圖這樣的:

#a reproducible example 
set.seed(42) 
x <- factor(sample(c("A", "B"), 20, TRUE)) 
y <- rnorm(20) 

#use plot.default explicitly to avoid using plot.factor implicitly 
plot.default(y ~ x, type = "p", 
      xlim = range(as.integer(unique(x))) + c(-0.4, 0.4), 
      xaxt = "n") 
axis(1, at = seq_along(levels(x)), labels = levels(x)) 

resulting plot

+0

Hi Roland。謝謝你。對不起,我對R相當陌生。我需要做些什麼才能更改我的數據的代碼? – glh

+0

'plot.default(Crude_rate〜Gender,data = melanoma,xlim = range(as.integer(unique(melanoma $ Gender)))+ c(-0.4,0.4)...)' – Roland

+0

謝謝,我也是需要在繪圖之後添加任何東西。默認(Crude_Rate〜性別,數據=黑色素瘤, xlim =範圍(as.integer(獨特的(黑素瘤$性別)))+ c(-0.4,0.4))? – glh

0

我會盡量展示你如何根據年齡計算原油價格。同樣,您可以繪製其他圖。爲了簡單起見,我已經向創建過程步步

input = NULL 
input$Age = rep(c("20-24","55-59","60-64","30-34"),4) 
input$Crude_Rate = runif(16) 
input = as.data.frame(input) 

library(dplyr) 
Byage <- input %>% 
     group_by(Age) %>% 
     summarise(n = n(), Crude_Rate = mean(Crude_Rate)) 
plot1 <-ggplot(input, aes(Age, Crude_Rate)) 
plot1 <-plot1 + geom_jitter(width = 0.5) 
plot1 <-plot1 + geom_point(data = Byage, colour = "red", size = 4) 
plot1 <-plot1 + geom_text(aes(y = -0.1, label = paste0("n = ", n)), Byage, size = 3) 

這將產生與年齡組爲x軸和Crude_Rate與每個組在底部中的樣本數,y軸一個很好的散點圖。

ScatterPlot of Age vs Crude_Rate with each age group mean Information

+0

謝謝你!不幸的是,當我嘗試時,我收到了很多錯誤。 – glh

+0

你能否詳細說明你所得到的錯誤。您需要安裝並加載ggplot2庫才能使用上述代碼。 – 9Heads

+0

它工作,我只需要輸入$ Crude_Rate = runif(361),因爲我有類別:input $ Age = rep(c(「<1」,「1-4」,「5-9」,「 10-14「,」15-19「,」20-24「,」25-29「,」30-34「,」35-39「,」40-44「,」45-49「,」 54,55-59,60-64,65-69,70-74,75-79,80-84,85+,19)。謝謝 – glh