【问题标题】:How can I create line chart for 'WorldPhones' dataset in R?如何在 R 中为“WorldPhones”数据集创建折线图?
【发布时间】:2020-05-10 07:28:35
【问题描述】:

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

【问题讨论】:

  • ts.plot(WorldPhones)plot.ts(WorldPhones) 对于初学者。

标签: r plot data-visualization linechart


【解决方案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() 

【讨论】:

  • 并且y轴标签应该是“用户(x 100,000)”。 >.
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 2017-08-14
    • 2018-10-19
    • 2018-11-09
    相关资源
    最近更新 更多