Reputation: 507
I'm trying to plot data from a dictionary. Each dictionary value will produce one line in the plot (values are lists of lists)
These lines have different number of points, and for this reason X ayis points are not sorted properly.
For example in the image above, point "3802814" is found for a line after points 3848766 & 3872755, and is plotted to the right side (not sorted properly as I want). I understand that dictionaries cannot be sorted as such, to overcome this.
The code is:
# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
for clk_name, clk_data in timing_of.items():
# Plot Xlabels with N-values in Y axis
plt.plot([col[0] for col in clk_data] , [col[1] for col in clk_data], label=clk_name)
plt.gca().legend(loc='center left', bbox_to_anchor=(1 , 0.8), prop={'size': 7})
plt.show()
How can I either: 1. sort the X ayis before showing the plot 2. alternatively, sort the data before I plot them?
Upvotes: 0
Views: 2012
Reputation: 507
As pointed by @ImportanceOfBeingErnest :
This had nothing to do with dictionary sorting. It was because my points were strings instead of numbers.
A simple casting to integer with int() solved it.
Upvotes: 0
Reputation: 2417
You could use numpy
import numpy as np
# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
X_all = np.array([])
Y_all = np.array([])
for clk_name, clk_data in timing_of.items():
X = np.array([col[0] for col in clk_data])
Y = np.array([col[1] for col in clk_data])
argsort = np.argsort(X)
X = X[argsort]
Y = Y[argsort]
# search the indexes to append in the right place
appendIndex = np.searchsorted(X_all, X)
X_all = np.insert(X_all , appendIndex, X)
Y_all = np.insert(Y_all , appendIndex, Y)
plt.plot(X_all , Y_all)
Upvotes: 1