Reputation: 67
I have a time series with records for years 1975-1985 and 2000-2005. I would like to have a single plot with only these years on it, i.e. without all the years 1986-1999 in between. On top of this, I'd like the years 1985 and 2000 to be not connected, and of different color.
Unfortunately, I only manage to produce a plot with all the years included. I am using Dataframes and Plots packages. Does anyone maybe know how to solve this issue?
Upvotes: 1
Views: 508
Reputation: 13800
It's not 100% clear from your question what your data looks like (are there missing
s in 1986-99?) and what your expected output is (do you want a gap in the middle of the plot?) but here are a couple of options:
# Packages to use
using Dates, DataFrames, Plots
# Example data
df = DataFrame(date = Date(1975):Year(1):Date(2005),
data = rand(31))
# Option 1 - plot with no data in the middle (straight line interpolation)
plot(df[.!in(1986:1999).(year.(df.date)), :date],
df[.!in(1986:1999).(year.(df.date)), :data])
# Option 2 - plot line in two parts with gap in the middle
plot(df[in(1970:1985).(year.(df.date)), :date],
df[in(1970:1985).(year.(df.date)), :data], color = "blue")
plot!(df[in(2000:2015).(year.(df.date)), :date],
df[in(2000:2015).(year.(df.date)), :data], label = "", color = "blue")
# Option 3 - plot continuous line and generate xticks manually
plot(df[.!in(1986:1999).(year.(df.date)), :data],
xticks = (1:length(df[.!in(1986:1999).(year.(df.date)), :date]),
year.(df[.!in(1986:1999).(year.(df.date)), :date])))
EDITED TO ADD:
If the data is actually missing, then option 3 can be produced even more simply by doing:
# Create example column with missing data
df[:, :data_missing] = allowmissing(df.data)
df[in(1986:1999).(year.(df.date)), :data_missing] .= missing
# Plot option 3
plot(df.date, df.data_missing)
EDITED AGAIN TO ADD: Finally if you want a gap in between the two and different colours, you need a variation of option 2:
plot(df[in([1970:1986; 2000:2015]).(year.(df.date)), :data_missing])
plot!(13:18, df[in(2000:2015).(year.(df.date)), :data_missing], label = "",
xticks = (1:18, year.(df[in([1970:1986; 2000:2015]).(year.(df.date)), :date])))
Upvotes: 4