简体   繁体   中英

Star Graph in R

I want to draw a star graph in R with dates and nb axis. The centre of the date is 02.07.2018.

Sample image:

在此处输入图像描述

My data:

dates   NB
3.01.2018   -80
15.01.2018  -75
8.02.2018   70
20.02.2018  65
4.03.2018   45
28.03.2018  20
9.04.2018   55
21.04.2018  60
3.05.2018   10
15.05.2018  40
8.06.2018   80
20.06.2018  50
02.07.2018 0
14.07.2018  -110
7.08.2018   50
19.08.2018  100
12.09.2018  45
24.09.2018  -20
6.10.2018   5
30.10.2018  20
11.11.2018  30
23.11.2018  -40
5.12.2018   -50
17.12.2018  -60

Where can I start? I don't have any idea. Thank you.

ggplot graph

This is the equivalent with ggplot :

library(ggplot2)
center <- subset(dd, dates=="2018-07-02")
ggplot(dd, aes(dates, NB, xend = center$dates, yend = center$NB)) +
  geom_segment(color="blue") +
  geom_point()

The graph will look like this:

在此处输入图像描述

Edit

If you want to include all dates to the x axis, you can use this code:

library(ggplot2)
center <- subset(dd, dates=="2018-07-02")
ggplot(dd, aes(dates, NB, xend = center$dates, yend = center$NB)) +
  geom_segment(color="blue") +
  geom_point() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
  scale_x_date(breaks = dd$dates)

Hope this helps.

First, make sure to read in your data and convert the date column to a proper date object in R.

dd <- read.table(text="
dates   NB
3.01.2018   -80
15.01.2018  -75
8.02.2018   70
20.02.2018  65
4.03.2018   45
28.03.2018  20
9.04.2018   55
21.04.2018  60
3.05.2018   10
15.05.2018  40
8.06.2018   80
20.06.2018  50
02.07.2018 0
14.07.2018  -110
7.08.2018   50
19.08.2018  100
12.09.2018  45
24.09.2018  -20
6.10.2018   5
30.10.2018  20
11.11.2018  30
23.11.2018  -40
5.12.2018   -50
17.12.2018  -60", header=T, stringsAsFactors=FALSE)
dd$dates <- as.Date(dd$dates, "%d.%m.%Y")

Here I just used read.table and then used as.Date to convert the first column to proper date values. This makes it easy to start the plot. For example

plot(NB~dates, dd)

Then to add all the lines, we can easily add a bunch of segments with a common end point. Here we grab your reference point, and then draw the segments.

plot(NB~dates, dd)
center <- subset(dd, dates=="2018-07-02")
segments(dd$dates, dd$NB, center$dates, center$NB)

Technically this is drawing the segments on top of the points. If you want to switch the order and make things blue, you can do

center <- subset(dd, dates=="2018-07-02")
plot(NB~dates, dd, type="n")
segments(dd$dates, dd$NB, center$dates, center$NB, col="blue")
points(dd$dates, dd$NB, pch=20)

在此处输入图像描述

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.

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