繁体   English   中英

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

[英]How can I create line chart for 'WorldPhones' dataset in R?

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

数据集帮助页面中的示例使用 matplot 给出了一个可爱的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() 

在此处输入图像描述

以下给出了您所追求的年份和大陆。 就我个人而言,我更喜欢这个 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM