我在R中的基础绘图系统中创建自定义轴有一个问题,我有以下数据框,我想要绘制一个趋势来显示每年的变化:
year <- c(2000, 2002, 2005, 2009)
values <- c(7332967, 5332780, 5135760, 3464206)
x <- data.frame(year, values)
## year values
## 1 2000 733296
## 2 2002 533278
## 3 2005 513576
## 4 2009 346420
我的第一次尝试是:
plot(x$year, x$value,
xlab = "Year",
ylab = "Value",
type = "b")
然而,这给了我数据框中四个值的x和y轴偏斜。我希望x轴只包含“年”列下的四个值,而y轴只包含“值”列下的四个值。
为此,我尝试创建自定义x和y轴但导致错误:
plot(x$year, x$value,
type = "b",
xaxt = "n",
yaxt = "n",
xlab = "Year",
ylab = "Values",
axis(1, at = 1:nrow(x), labels = x$year),
axis(2, at = 1:nrow(x), labels = x$value))
"Error in plot.window(...) : invalid 'xlim' value"
和
plot(x$year, x$value,
type = "b",
xaxt = "n",
yaxt = "n",
xlab = "Year",
ylab = "Values",
axis(1, at = 1:nrow(x), labels = x$year),
axis(2, at = 1:nrow(x), labels = x$value),
xlim = c(min(data_plot$year), max(data_plot$year)),
ylim = c(min(data_plot$Emissions), max(data_plot$Emissions)))
"Error in strsplit(log, NULL) : non-character argument"
我是R的新手并尝试在各种网站上搜索解决方案,但是,似乎没有什么能解决这个问题,所以提供的任何帮助都会非常感激。
答案 0 :(得分:0)
axis
是一个单独的函数,而不是plot
的参数,请尝试以下操作:
# First make some extra space on the left for the long numeric axis labels
par(mar=c(5, 6, 1, 1))
# Now plot the points, but suppress the axes
plot(x$year, x$values, xaxt='n', yaxt='n', xlab='Year', ylab='', type='b')
# Add the axes
axis(1, at=x$year, labels=x$year, cex.axis=0.8)
axis(2, at=x$values, labels=x$values, las=1, cex.axis=0.8)
# Add the y label a bit further away from the axis
title(ylab='Value', line=4)