Axis Does Not Plot with Date Labels

Axis does not plot with date labels

First, create the plot without axes (axes = FALSE):

plot(A ~ Dates, fData,  type = "o", col = "red", ylim = range, pch = 10,
axes = FALSE)
points(B ~ Dates, fData, type = "o", col = "green", pch = 11)
points(C ~ Dates, fData, type = "o", col = "black", pch = 12)
points(D ~ Dates, fData, type = "o", col = "blue", pch = 13)
points(E ~ Dates, fData, type = "o", col = "magenta", pch = 14)

You can't use axis.Date for the x-axis since you want slanted labels. You have to combine axis (for the tick marks) and text for the labels: Here, format is used the create the labels:

axis(side = 1, at = Labels, labels = FALSE) 
text(x = Labels, y = par("usr")[3] - 70000, labels = format(Labels, "%m/%y"),
srt = 45, pos = 1, xpd = TRUE)

Now, you have to create the y-axis. First, we need a vector of tick positions (ticksY) and a vector of labels (LabelsY). The values are in the specified format:

ticksY <- seq(0, max(range), 100000)
LabelsY <- paste("$", format(ticksY, scientific = FALSE, big.mark = ","))
axis(side = 2, at = ticksY, labels = LabelsY)

Sample Image

R X-axis Date Labels using plot()

With plots it's very hard to reproduce results with out sample data. Here's a sample I'll use

dd<-data.frame(
saldt=seq(as.Date("1999-01-01"), as.Date("2014-01-10"), by="6 mon"),
salpr = cumsum(rnorm(31))
)

A simple plot with

with(dd, plot(saldt, salpr))

produces a few year marks

Sample Image

If i wanted more control, I could use axis.Date as you alluded to

with(dd, plot(saldt, salpr, xaxt="n"))
axis.Date(1, at=seq(min(dd$saldt), max(dd$saldt), by="30 mon"), format="%m-%Y")

which gives

Sample Image

note that xlim will only zoom in parts of the plot. It is not directly connected to the axis labels but the axis labels will adjust to provide a "pretty" range to cover the data that is plotted. Doing just

xlim=c(as.Date("1999-01-01"),as.Date("2014-01-01"))

is the correct way to zoom the plot. No need for conversion to numeric or POSIXct.

Pandas dataframe plot(): x-axis date labels display but not data

  • Dataset is at Assets: Total Assets: Total Assets (Less Eliminations from Consolidation): Wednesday Level (WALCL)
  • Verify the DATE column is in a datetime format by using parse_dates with .read_csv.

Set DATE as the index

import pandas as pd
import numpy as np

# verify the DATE column is in a datetime format and set it as the index
dfData = pd.read_csv('WALCL.csv', skiprows=0, parse_dates=['DATE'], index_col='DATE')

# plot the data
ax = dfData.plot(figsize=(20, 8))

datemin = np.datetime64(dfData.index.min(), 'Y')
datemax = np.datetime64(dfData.index.max(), 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)

Sample Image

Leave DATE as a column

import pandas as pd

# read file
dfData = pd.read_csv('WALCL.csv', skiprows=0, parse_dates=['DATE'])

# plot data
ax = dfData.plot('DATE', 'WALCL', figsize=(20, 8))

Sample Image

Custom breaks and labels are missing on date axis

You're running into problems using dates. They are not really continuous nor discrete. So neither scale_x_continous nor scale_x_discrete will work like a charm.
The challenge is the conversion between character and date class.
In my example, I am keeping everything as Date, from the very beginning creating "Test" as Date class. In order to make your code a bit clearer, I created the break vector beforehand, using seq. There are certainly more elegany ways out there. I've also removed all your redundant code which is not pertinent to the question.

library(tidyverse)

Test = as.Date('2010-05-02') #makes your life easier
data = data.frame(x=-28:28)
data$date = Test + data$x
data$y = sample(1:6, size=57, replace=TRUE)

my_breaks <- c(seq(Test-28,'2 weeks', to =Test),
seq(Test,'2 weeks', to = Test + 28))

ggplot(data) +
geom_point(aes(date, y)) +
geom_vline(xintercept = as.Date(Test)) +
scale_x_date(breaks = my_breaks)

Sample Image

Created on 2019-11-28 by the reprex package (v0.3.0)

Matplotlib plot_date x-axis labels off by days and partially missing

To fix the tick locations to exactly the dates that the data points are located at, you need to use a Locator as well as a Formatter.

The locator should be a matplotlib.ticker.FixedLocator which sets the locations according to the input data. The formatter can be any matplotlib.dates formatter.

data = [[u'2017-07-03', 427],
[u'2017-07-10', 201],
[u'2017-07-17', 594],
[u'2017-07-24', 525],
[u'2017-07-31', 239],
[u'2017-08-07', 437]]

import matplotlib.pyplot as plt
import matplotlib.dates
import matplotlib.ticker
import datetime

x,y = zip(*data)
f = lambda s: datetime.datetime.strptime(s, '%Y-%m-%d')
x = list(map(f, x))

fig, ax = plt.subplots()
ax.plot(x,y)

loc = matplotlib.ticker.FixedLocator(matplotlib.dates.date2num(x) )
fmt = matplotlib.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(fmt)

fig.autofmt_xdate()
plt.show()

Sample Image



Related Topics



Leave a reply



Submit