Adapt 2D-plot tick label attributes to dates
Is there a way to access ticks labels to rotate them? I've tried Graphics.matplotlib()
and set_rotation()
, but this doesn't seem to produce changes. Am I doing wrong things?
In the example below, the formatter and locator are working correctly, but the problem is all labels are oriented horizontally, messing all together since each tick label is a date and therefore quite long. Need to rotate them.
import csv
from datetime import datetime
from matplotlib import ticker
from matplotlib import dates
data = [('04/22/20', '04/23/20', '04/24/20','04/25/20','04/26/20', '04/27/20'),
(20, 40, 80, 160, 320, 640)]
labels = data[0]
labels = map(lambda x: dates.date2num(datetime.strptime(x, '%m/%d/%y')), labels)
labels = list(labels)
values = data[1]
values = map(lambda x: int(x), values)
# Z is a list of [(x1, y1), (x2, y2)...]
# x1, x2, ... are dates
# y1, y2, ... are values
Z = zip(labels, values)
Z = list(Z)
p = list_plot(Z, ticks=[1, None],
tick_formatter=[dates.DateFormatter('%d.%m.%Y'), None],
axes_labels=['Days', '$\\log \\;{N}$'], plotjoined=True,
thickness=2, figsize=4, scale='semilogy')
G = p.matplotlib()
labels = G.axes[0].xaxis.get_ticklabels()
labels = list(labels)
for label in labels:
label.set_rotation(45)
p
This outputs the plot with an ugly x-axis on which all the dates are messed up. How to fix that?
A minimal example that can by copy-pasted in a fresh Sage session helps others get started on an answering a question, therefore increasing the chances of getting an answer. In this case,
dates.DateFormatter
will workZ
(with just enough dates to illustrate the problem)Hello, thank you for your response. I've added the information needed to comply.
Following what is explained in this link, it seems the following should work:
but the last line returns an error because
figure.canvas
is NoneYes, thanks for this answer. I've already tried that with the same result. But this example is for pure matplotlib, not the sage
Graphics
object. I would like to know, what does thatmatplotlib()
exactly do? I even tried:to draw the plot on the new figure provided, but this doesn't work for me. So, the question is, is this
matplotlib()
function supposed to give the access top
attributes, which were previosly set when the plot was created, and should the changes made on the figure effect onto the plot? And is the plot is supposed to be redrawn on the new figure when the plot is passed as an argument to matplotlib()?Suggestion: format dates following the international standard ISO 8601.