How to apply plt.xticks for all the subplots? - pandas

I am trying to do some simple visualizations using seaborn.
def show_figures():
sns.barplot(ax=axes[0, 0], x=df['Genre'], y=df['NA_Sales'])
sns.barplot(ax=axes[0, 1], x=df['Genre'], y=df['EU_Sales'])
sns.barplot(ax=axes[1, 0], x=df['Genre'], y=df['JP_Sales'])
sns.barplot(ax=axes[1, 1], x=df['Genre'], y=df['Other_Sales'])
show_figures()
plt.xticks(rotation=70)
plt.show()
I wanted to rotate the xticks of axes[1, 0] too, but I got this:
How can we rotate the xticks of all subplots ?
Thank you!

Related

Generate scatter plot

I executed almost all the lines of code mentioned in this article.
https://rubikscode.net/2020/11/09/ml-optimization-pt-3-hyperparameter-optimization-with-python/
But I did not understand how the charts are generated from the model.
plt.plot(X_test, y_test, ls="none", marker=".", ms=12)
I tried this plot method and it generates the chart. But it is not anywhere close to the one shown in the article. and sns.scatterplot(X_test, y_test) returns an error.
From github:
plt.figure(figsize=(11, 5))
plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='orange', label='Adelie')
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='gray', label='Chinstrap')
plt.scatter(X[y == 2][:, 0], X[y == 2][:, 1], color='black', label='Gentoo')
plt.legend();
source: https://github.com/NMZivkovic/ml_optimizers_pt3_hyperparameter_optimization/blob/master/ML%20Optimization%20pt.3%20%E2%80%93%20Hyperparameter%20Optimization%20with%20Python.ipynb

Pyplot won't clear figure after using add_artist

In this toy example, I add Mario to a plot using add_artist. When I do that, I can't seem to clear the figure. Python throws RuntimeError: Can not put single artist in more than one figure when it tries to add mario to the second plot (02.png). Why is this happening? How can I avoid this error? I tried sending a copy of the AnnotationBbox to add_artist, following this approach, but it did not work.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
vortexRF = plt.imread('./mario.png')
imagebox = OffsetImage(vortexRF, zoom=0.03)
for ii in range(3):
fig, ax = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.6, hspace=0.5)
for jj in range(2):
for kk in range(2):
ax[jj, kk].plot([0, 1], [0, 1], label='1')
ax[jj, kk].plot([0, 1], [0, 1], label='2', ls='--')
ax[1, 0].legend(loc='upper center', bbox_to_anchor=(.08, 2.85))
if True: # Switch to control if we add mario
ab = AnnotationBbox(imagebox, (0, 0), frameon=False)
cbar_ax = fig.add_axes([0.7, .92, 0.1, 0.1])
cbar_ax.add_artist(ab)
cbar_ax.axis('off')
plt.savefig('./%02d' % ii)
# attempt to clear figure
plt.clf()
plt.cla()
plt.close('all')
ab.remove()
If you are trying to make Mario run in a rush :) like shown below, I think you need to make a new 'imagebox' every time you add to the axis.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
vortexRF = plt.imread('mario.png')
for ii in range(9):
fig, ax = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.6, hspace=0.5)
for jj in range(2):
for kk in range(2):
ax[jj, kk].plot([0, 1], [0, 1], label='1')
ax[jj, kk].plot([0, 1], [0, 1], label='2', ls='--')
ax[1, 0].legend(loc='upper center', bbox_to_anchor=(.08, 2.85))
if True: # Switch to control if we add mario
imagebox = OffsetImage(vortexRF, zoom=0.03)
ab = AnnotationBbox(imagebox, (0, 0), frameon=False)
cbar_ax = fig.add_axes([0.1+0.1*ii, .92, 0.1, 0.1])
cbar_ax.add_artist(ab)
cbar_ax.axis('off')
plt.savefig(str(ii)+'.png')
plt.show()

Set_xlabel is in invalid in ax[0, 0] when drawing 4 subplots in one plot

I get some codes as followed and I want to draw 4 subplots in one plot.
fig, ax = plt.subplots(nrows=2, ncols=2)
# ax[0, 0]
sns.countplot(train_df['Survived'], ax=ax[0, 0])
ax[0, 0].set_xlabel('Survived')
# ax[0, 1]
ax[0, 1].pie(train_df['Survived'].value_counts(), autopct='%1.1f%%')
ax[0, 1].set_aspect('equal')
ax[0, 1].set_xlabel('Survived')
# ax[1, 0]
sns.countplot(train_df['Pclass'].values, ax=ax[1, 0])
ax[1, 0].set_xlabel('Pclass')
# ax[1, 1]
ax[1, 1].pie(train_df['Pclass'].value_counts(), autopct='%1.1f%%')
ax[1, 1].set_aspect('equal')
ax[1, 1].set_xlabel('Pclass')
plt.savefig('four_subplots_in_one_figure.jpg')
But what I find is that I the first subplot in ax[0,0] doesn't have an x_label even if I have set it on purpose.
The data I use is from Titanic in Kaggle.
So if not mind could anyone tell me how to set it right?
Thanks in advance.
Your xlabel is simply hidden under the bottom plot.
You can use plt.tight_layout() at the end of your script to automatically adjust the sizes of each subplots to see their respective labels.

squared-off line plot matplotlib

How do I generate a line graph in Matplotlib where lines connecting the data points are only vertical and horizontal, not diagonal, giving a "blocky" look?
Note that this is sometimes called zero order extrapolation.
MWE
import matplotlib.pyplot as plt
x = [1, 3, 5, 7]
y = [2, 0, 4, 1]
plt.plot(x, y)
This gives:
and I want:
I think you are looking for plt.step. Here are some examples.

Mayavi doesn't draw lines

I want to draw very simple graph with 4 nodes and 3 edges:
from numpy import array, vstack
from mayavi import mlab
mlab.figure(1, bgcolor=(1, 0.9, 1))
mlab.clf()
x = array([0, 3, 2, 3])
y = array([0, 4, 5, 1])
z = array([0, 0, 1, 1])
color = array([0.1, 0.3, 0.5, 0.7])
pts = mlab.points3d(x, y, z,
color,
scale_factor=1,
scale_mode='none',
colormap='Blues',
resolution=20)
edges = vstack([[0, 1], [0, 2], [0, 3]])
pts.mlab_source.dataset.lines = edges
tube = mlab.pipeline.tube(pts, tube_radius=0.1, tube_sides=7)
mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8))
mlab.show()
It returns that:
Why edges are missing?
There is a bug in Mayavi about this. It is related to unsynchronized changes with VTK and are thus a bit hard to pinpoint. There is a discussion on Mayavi's GitHub https://github.com/enthought/mayavi/issues/388
The bug also shows up with the protein.py example that comes up with Mayavi and it is fixed there by adding
pts.mlab_source.update()
after setting the lines. It is fixed online for the example at https://github.com/enthought/mayavi/commit/afb17fceafe787c8260ca7a37fbb3b8c2fbfd36c
Using the fix did not work for me though but you might try.