What are some possible reasons that axes labels for a graph won't show up? The graph itself works fine but the labels don't.
f= open("test1T.txt")
t1T = f.read()
x= [min_crib_dist("squeamish ossifrage",sub_cipher(t1T,rand_dict())) for i in range(10000)]
plt.xlabel = ('Minimum Hamming Distance')
plt.ylabel = "Number of Simulations"
plt.hist(x, bins=10)
plt.show()
xlabel and ylabel are functions - you can't set the values directly. Your code should read as follows:
f= open("test1T.txt")
t1T = f.read()
x= [min_crib_dist("squeamish ossifrage",sub_cipher(t1T,rand_dict())) for i in range(10000)]
plt.xlabel('Minimum Hamming Distance')
plt.ylabel("Number of Simulations")
plt.hist(x, bins=10)
plt.show()
See reference here.
Related
I have several plots and one of these showed below:
Example plot
Problem is I have many plots and I need to put the legend differently according to the position where x=0 and line of x=0 may vary in different plots.
How can I achieve this?
besides, bbox_to_anchor just allow me locate relatively to the fig, but have no idea of the inside (x,y) coordinate.
This is the part plotting:
ax.errorbar(x=x, y=y_erd, yerr=e_erd, fmt='-o',ecolor='orange',elinewidth=1,ms=5,mfc='wheat',mec='salmon',capsize=3)
ax.errorbar(x=x, y=y_ers, yerr=e_ers, fmt='-o',ecolor='blue',elinewidth=1,ms=5,mfc='wheat',mec='salmon',capsize=3)
ax.legend(['ERD', 'ERS'], loc="upper left", bbox_to_anchor=(1, 0.85),fontsize='x-small')
ax.axhline(y=0, color='r', linestyle='--')
We have created a code to calculate the zero position of the x and y axes using a simple sample as an example. First, get the tick values for each axis. Then, use the obtained value to get the index of zero. The next step is to calculate the position of the tick marks for the difference between the minimum and maximum values. From the array, we obtain the coordinates based on the zero index we obtained earlier. Set the obtained coordinates to bbox_to_anchor=[].
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 500)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, label='x=0,y=0')
xticks, yticks = ax.get_xticks(), ax.get_yticks()
xpos, ypos = 0, 0
for i,(x,y) in enumerate(zip(xticks, yticks)):
if x == 0:
xpos = i
if y == 0:
ypos = i
print(xpos, ypos)
x_min, x_max = ax.get_xlim()
xticks = [(tick - x_min)/(x_max - x_min) for tick in xticks]
y_min, y_max = ax.get_ylim()
yticks = [(tick - y_min)/(y_max - y_min) for tick in yticks]
print(xticks[xpos], yticks[ypos])
ax.legend(bbox_to_anchor=[xticks[xpos], yticks[ypos]], loc='center')
plt.show()
A quite basic question about ticks' labels for x and y-axis. According to this code
fig, axes = plt.subplots(6,12, figsize=(50, 24), constrained_layout=True, sharex=True , sharey=True)
fig.subplots_adjust(hspace = .5, wspace=.5)
custom_xlim = (-1, 1)
custom_ylim = (-0.2,0.2)
for i in range(72):
x_data = ctheta[i]
y_data = phi[i]
y_err = err_phi[i]
ax = fig.add_subplot(6, 12, i+1)
ax.plot(x_data_new, bspl(x_data_new))
ax.axis('off')
ax.errorbar(x_data,y_data, yerr=y_err, fmt="o")
ax.set_xlim(custom_xlim)
ax.set_ylim(custom_ylim)
I get the following output:
With y labels for plots on the first column and x labels for theone along the last line, although I call them off.
Any idea?
As #BigBen wrote in their comment, your issue is caused by you adding axes to your figure twice, once via fig, axes = plt.subplots() and then once again within your loop via fig.add_subplot(). As a result, the first set of axes is still visible even after you applied .axis('off') to the second set.
Instead of the latter, you could change your loop to:
for i in range(6):
for j in range(12):
ax = axes[i,j] # these are the axes created via plt.subplots(6,12,...)
ax.axis('off')
# … your other code here
I've plotted a confusion matrix with scikit-learn / matplotlib thanks to different code examples I found on the web, but I'm stuck at finding how to add space between the xticklabels and the main title. As you can see on the image below, the plot title and the xticklabels are overlapping (+ the ylabel 'True' is cut out).
Link to my confusion matrix image
Here is the function I use:
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
PLOTS = '/plots/' # Output folder
def plt_confusion_matrix(y_test, y_pred, normalize=False, title="Confusion matrix"):
"""
Plots a nice confusion matrix.
:param y_test: list of predicted labels
:param y_pred: list of labels that should have been predicted.
:param normalize: boolean. If False, the plots shows the number of sentences predicted.
If True, shows the percentage of sentences predicted.
:param title: string. Title of the plot.
:return: Nothing but saves the plot as a PNG file and shows it.
"""
labels = list(set(y_pred))
cm = confusion_matrix(y_test, y_pred, labels)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm, cmap=plt.cm.binary, interpolation='nearest')
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig.suptitle(title, fontsize=14, wrap=True)
fig.colorbar(cax)
ax.set_xticklabels([''] + labels, rotation=45)
ax.set_yticklabels([''] + labels)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.subplots_adjust(hspace=0.6)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
plt.savefig(PLOTS + title)
plt.show()
I had to rotate the xticklabels because they are too long and otherwise overlapping each other horizontally, and I had to wrap the title because it is also too long and could not otherwise be displayed entirely in the image.
I've seen in another post that xticklabels can also be placed underneath the figure (like in this stackoverflow post), so maybe it could be a solution, however I haven't understood how to make it.
How do I solve the problem?
either to add some space between the title and the xticklabels
(making them appear entirely btw);
or to make the ylabel 'True' visible
or to move the xticklabels under the figure.
Edit : I tried both of geekzeus solutions, without success...
Result with geekzeus' 1st solution : See confusion matrix
Result with geekzeus' 2nd solution : See confusion matrix
Do it like this
ax.set_xlabel('Predicted labels')
ax.set_ylabel('True labels')
ax.set_title('Confusion Matrix')
#xaxisticks
ax.xaxis.set_ticklabels(['A', 'B'])
#yaxis ticks
ax.yaxis.set_ticklabels(['B', 'A'])
OR
use seaborn with matplotlib,you can also directly provide list variable to ticks
import seaborn as sns
import matplotlib.pyplot as plt
cm = confusion_matrix(true_classes, predicted_classes)
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted labels')
ax.set_ylabel('True labels')
ax.set_title('Confusion Matrix')
ax.xaxis.set_ticklabels(['A', 'B'])
ax.yaxis.set_ticklabels(['B', 'A'])
You can specify the location of the title using parameters x and y. If you tweak the values of y, the desired plot can be generated.
fig.suptitle(title, fontsize=14, wrap=True, y=1.2)
I am trying to emulate the span selector for the data I have according to the example shown here (https://matplotlib.org/examples/widgets/span_selector.html).
However, my data is in a dataframe & not an array.
When I plot the data by itself with the using the code below
input_month='2017-06'
plt.close('all')
KPI_ue_data.loc[input_month].plot(x='Order_Type', y='#_Days_#_Post_stream')
plt.show()
the data chart is shown perfectly.
However when i am trying to put this into a subplot with the code below (only first two lines are added & ax=ax in the plot line), nothing shows up. I get no error either!!! can anyone help?
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211, facecolor='#FFFFCC')
input_month='2017-06'
plt.close('all')
KPI_ue_data.loc[input_month].plot(x='Order_Type', y='#_Days_#_Post_stream',ax=ax)
plt.show()
I usually just set x, y from the dataframe and use ax.plot(x, y). For your code, it should look something like this:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211, facecolor='#FFFFCC')
input_month='2017-06'
#plt.close('all')
x = KPI_ue_data.loc[(input_month), 'Order_Type']
y = KPI_ue_data.loc[(input_month), '#_Days_#_Post_stream']
ax.plot(x, y)
plt.show()
I made a histogram of array x with each bar color-coded according to the average of another property y in that bin. How can I make an associated colorbar?
norm = matplotlib.colors.Normalize(vmin=np.min(y), vmax=np.max(y))
cmap = cm.jet
m = cm.ScalarMappable(norm=norm, cmap=cmap)
fig = plt.figure()
n, bins, patches= plt.hist(x, bins = np.arange(0,max_x) + 0.5)
for i in range(np.size(patches)):
plt.setp(patches[i],color=m.to_rgba(y[i]))
plt.colorbar(norm=norm,cmap=cmap)
plt.show()
This colorbar returns an error message " No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf)."
Found a way using a "ScalarMappable":
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm._A = []
plt.colorbar(sm)