Issue
I have this code in a jupyter notebook cell:
%reset -f
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
import math
x_labels=['p0','p1','p2']
data=[{'p0':1,'p2':5},{'p0':1,'p1':2},{'p1':3,'p2':4}]
fig_all, axe_all=plt.subplots()
#axe_all.set_xticks(range(1,len(x_labels)+1))
#axe_all.set_xticklabels(x_labels)
for row in data:
data_values=row.values()
plot_ticks=row.keys()
fig, axe=plt.subplots()
axe.plot(plot_ticks,data_values,marker='o')
axe_all.plot(plot_ticks,data_values,marker='o')
it generates the following plots:
There are some issues with these plots that I want to know how I can fix:
1- On all plot, P2 is before P1. How can Make sure that always P2 is after P1 and matched to the order that I have in x_labels? I tried to fix the issue with this line (it is commented out in the code above)
axe_all.set_xticklabels(x_labels)
But I am getting this warning:
<ipython-input-16-1083d5a1877e>:14: UserWarning: FixedFormatter should only be used together with FixedLocator axe_all.set_xticklabels(x_labels)
to fix it I added this line to the code:
axe_all.set_xticks(range(1,len(fiels_marker_names)+1))
but then it generates the plot with the wrong order of x labels.
2- How can make sure that all plots have the same axis extent?
Extended question: Where can I share line Jupyter notebooks for this question that others can test, view and change it to get the required result?
Solution
An idea is to initialize the categorical axes with a dummy plot using the x-values in the desired order. An explicit set_xlim
is needed to show all ticks. It could look like:
x_labels = ['p0', 'p1', 'p2']
ax.plot(xlabels, [np.nan]*len(xlabels))
ax.set_xlim(-0.5, len(xlabels)-0.5)
When more axes need to be initialized, it helps to create a function:
import matplotlib.pyplot as plt
def init_categorical_xticks(x_labels, ax=None):
if hasattr(ax, "__iter__"):
# when there is a list or array of axes, initialize each of them (should also work for 2D lists)
for axi in ax:
init_categorical_xticks(x_labels, axi)
else:
ax = ax or plt.gca() # use current ax when ax is None
ax.plot(x_labels, [np.nan] * len(x_labels))
ax.set_xlim(-0.5, len(x_labels) - 0.5)
x_labels = ['p0', 'p1', 'p2']
data = [{'p0': 1, 'p2': 5}, {'p0': 1, 'p1': 2}, {'p1': 3, 'p2': 4}]
fig_all, axe_all = plt.subplots()
init_categorical_xticks(x_labels)
for row in data:
data_values = row.values()
plot_ticks = row.keys()
fig, axe = plt.subplots()
init_categorical_xticks(x_labels, axe)
axe.plot(plot_ticks, data_values, marker='o')
axe_all.plot(plot_ticks, data_values, marker='o')
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.