简体   繁体   English

使用 ggplot2 在 R 上创建水平线图:显示百分比变化

[英]Create horizon chart on R using ggplot2: show percentage change

I am a beginner at this and am really lost about it.我是这方面的初学者,我真的很迷茫。

I would like to create a horizon chart that shows the percentage change in sales for the different towns using ggplot2 and R.我想创建一个水平图表,显示使用 ggplot2 和 R 的不同城镇的销售额百分比变化。 Would anyone guide me in the approach I can take to create the chart?有人可以指导我创建图表的方法吗?

The data that I have looks like this.我拥有的数据看起来像这样。 在此处输入图像描述

This is the type of chart I would like to do.这是我想做的图表类型。 (source: https://harmoniccode.blogspot.com/2017/11/friday-fun-li-horizon-charts.html ) (来源: https://harmoniccode.blogspot.com/2017/11/friday-fun-li-horizon-charts.html 在此处输入图像描述

Thanks in advance for any help given!提前感谢您提供的任何帮助!

Edit: here's a sample code of the data:编辑:这是数据的示例代码:

x <- data.frame(
  "town" =c('sad','sad','sad','sad','happy','happy','happy','happy'),
  "month"=c("2017-01","2017-02","2017-03","2017-04","2017-01","2017-02","2017-03","2017-04"),
  "median_sales" = c(336500,355000,375000,395000,359000,361500,36000,375000),
  "percentage_change" = c(NA,5.4977712,5.6338028,5.3333333,NA,0.6963788,-0.4149378,  4.1666667
))

x <-
  x %>%
  mutate(month = floor_date(as_date(as.yearmon(month)), "month"))

It would be helpful to give an example that will result in a reasonable plot, and to provide your example data as data rather than an image.给出一个可以产生合理 plot 的示例并将您的示例数据作为数据而不是图像提供会很有帮助。

If you google 'horizon plot' the first answer should give you what you need.如果你用谷歌搜索“地平线图”,第一个答案应该会给你你需要的东西。

Here is a simple example based on the data you gave:这是一个基于您提供的数据的简单示例:

library(latticeExtra)

sales.ts <- ts(matrix(sales$median_sales, ncol=2), names = c("sad", "happy"),
               start = c(2017, 1), frequency = 365)

horizonplot(sales.ts)

I think this is correctly presenting your results, but again hard to tell as you haven't given a realistic dataset.我认为这正确地呈现了您的结果,但由于您没有提供真实的数据集,因此很难说清楚。

UPDATE: based on the data provided, this is the answer.更新:根据提供的数据,这就是答案。 Again, as you've only provided one time point a horizonplot is probably not what you want.同样,由于您只提供了一个时间点,因此水平图可能不是您想要的。 They are designed to plot time series.它们被设计为 plot 时间序列。

x.ts <- ts(matrix(x$median_sales, ncol=2), names = c("sad", "happy"),
                  start = c(2015, 1), frequency = 12)

horizonplot(x.ts)

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

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