为什么我输入到R绘图函数的数据会发生变化?

时间:2019-05-13 12:14:09

标签: r plot

每当我尝试在R中创建折线图以显示数据时,我希望它的显示方式出现错误,因为它似乎未使用该轴的给定数据。目标是能够显示它,以便在x轴上显示过去的年数,并在y轴上显示这些年内的死亡人数,但是无论何时我尝试这样做,R都会更改死亡数据,但是如果我反转数据,它将正确打印数据。

我试图删除一些非必要信息,并试图交换数据位置。

totals = 21,945 22,321 22,849 22,425 22,856 23,968 23,500 24,514 23,584 24,473 25,801 27,335 26,316 27,289 27,414 28,300 27,901 28,704 29,782 29,690 31,555
years = 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017

plot(totals, years, type="l", xlab = "Years", ylab = "Deaths", main = "Deaths Over the Years")
plot(years, totals, type="l", xlab = "Years", ylab = "Deaths", main = "Deaths Over the Years")

所示的第一行代码以错误的值样式显示了与我所希望的图形相反的图形,但是它使用了正确的数据: inversed graph 第二行以正确的样式显示数据,并且应该以正确的方式显示数据,然而,在正确地显示Years轴的同时,死亡轴上的数据已减少了不应该发生的显着量: correctly formatted graph (corrupted data)

1 个答案:

答案 0 :(得分:2)

请向reproducible example提供实际数据。这确实可以帮助您获得帮助。从您的示例中,我认为您需要了解正在使用的变量的类型。在这种情况下,characternumeric变量与factors之间的差异很重要。

我可以使用以下代码复制您的图,其中复制您发布的值,然后使用scan函数输入。您的数据已放置在数据框中。

Years <- scan() # copy and paste 'years' data
Deaths <- scan(what = "", sep = " ") # copy and paste 'totals' (deaths)
df <- data.frame(Years, Deaths)

我正在将公式界面用于plot(y ~ x)plot(x, y)相同的基本绘图。请注意已完成了再现图的操作。

opar <- par(mfrow = c(1, 2))
main <- "Deaths Over the Years"
plot(Years ~ Deaths, df, main = main, ylab = "Deaths", xlab = "Years")
plot(as.numeric(Deaths) ~ Years, df, type = "l", main = main, ylab = "Deaths")
par(opar)

Reproduction of plots

“年份”的值保留逗号。因此,它们被导入为character变量,并转换为一个因子。当因子转换为numeric类型时,它们将成为代表因子级别序列的整数。对于您的示例,一个简单的解决方案是删除逗号并将character变量转换为numeric变量。

Deaths2 <- as.numeric(gsub(",", "", Deaths))
df$Deaths2 <- Deaths2 # add this variable to the data frame
plot(Deaths2 ~ Years, df, type = "l", main = main, ylab = "Deaths")