Reputation: 217
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.
Upvotes: 2
Views: 541
Reputation: 3632
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:
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.
Upvotes: 3
Reputation: 206401
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)
Upvotes: 1