如何在R中为'WorldPhones'数据集创建折线图?

问题描述 投票:0回答:1

如何在R中为'WorldPhones'数据集创建折线图?数据集的类别是 "矩阵""数组"。我想绘制1956-1961年间北美、亚洲和欧洲的电话数量的折线图,如何为 "WorldPhones "数据集创建折线图?

r plot data-visualization linechart
1个回答
1
投票

在数据集的帮助页面中的例子给出了一个可爱的图,使用了 matplot. 如果想看一些更有趣的东西,你可以试试ggplot。

library(tidyr)   # For pivoting the data into long form 
library(tibble)  # For converting the rownames (Year) to a column
library(scales)  # For scaing the y-axis and labels
library(ggplot2) # For the plot

WorldPhones %>%
  as.data.frame() %>%
  rownames_to_column("Year") %>%
  pivot_longer(cols=-Year, names_to="Country", values_to="Users") %>%
  ggplot(aes(Year, Users, group=Country, col=Country)) +
  geom_line() +
  scale_y_log10(n.breaks=5, labels = trans_format("log10", math_format(10^.x))) +
  theme_minimal() 

enter image description here


1
投票

下面给出了你想要的年份和大陆。 就我个人而言,我更喜欢这种简单的Base-R代码和对图表外观的精细控制,尽管美是看在眼里的。

WP <- WorldPhones[as.character(1956:1961), c("N.Amer", "Asia", "Europe")]
matplot(x = rownames(WP), y = WP/1000, 
        type = "b", pch = 16, lty = 1, lwd = 2, 
        log = "y", ylim = c(2, 100),
        main = "World phones data (AT&T 1961)",
        xlab = "Year", ylab = "Number of telephones (millons)")
legend("bottom", legend = colnames(WP), horiz = TRUE, 
       lwd = 2, pch = 16, col = 1:3)
© www.soinside.com 2019 - 2024. All rights reserved.