How can I create line chart for 'WorldPhones' dataset in R? The dataset is of class - "matrix" "array". I want to plot a line chart for the number of telephones in North America, Asia and Europe between 1956-1961.
The example in the help page for the dataset gives a lovely plot using matplot
. For something slightly more pleasing, you can try 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()
The following gives the years and continents you are after. Personally I prefer simplicity of this base-R code and the fine-grained control this gives you over the look of the chart, though beauty is in the eye of the beholder!
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.