How to label charts when using multiple matplotlib figures? - python

I would like to know how can I label multiple matplotlib charts, please?
If I call .xlabel(), or .ylabel() on plt directly only one of the graphs gets labelled, however if I call the functions on the figure, I get an error.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
N_points = 100000
dist1 = rng.standard_normal(N_points)
fig1 = plt.figure()
axis = fig1.add_subplot(1,1,1)
axis.grid()
fig2 = plt.figure()
ax = fig2.add_subplot(1,1,1)
ax.grid()
plt.xlabel('X AXIS')
plt.ylabel('Y AXIS')
axis.hist(dist1)
ax.hist(dist1)
plt.show()

You can set the labels using the Axes (axis and ax in you case) with the set_xlabel and set_ylabel methods. E.g.,
# add labels onto the first plot
axis.set_xlabel("X AXIS")
axis.set_ylabel("X AXIS")
...
ax.set_xlabel("Another X AXIS")
ax.set_ylabel("Another X AXIS")
Note that you're currently also creating two separate figures. If you want two plots on the same figure you could do:
fig, ax = plt.subplots(2, 1)
Then ax[0] will be the first axis onto which you can plot and ax[1] will be the second.

Related

Combine 2 kde-functions in one plot in seaborn

I have the following code for plotting the histogram and the kde-functions (Kernel density estimation) of a training and validation dataset:
#Plot histograms
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
displot_dataTrain=sns.displot(data_train, bins='auto', kde=True)
displot_dataTrain._legend.remove()
plt.ylabel('Count')
plt.xlabel('Training Data')
plt.title("Histogram Training Data")
plt.show()
displot_dataValid =sns.displot(data_valid, bins='auto', kde=True)
displot_dataValid._legend.remove()
plt.ylabel('Count')
plt.xlabel('Validation Data')
plt.title("Histogram Validation Data")
plt.show()
# Try to plot the kde-functions together --> yields an AttributeError
X1 = np.linspace(data_train.min(), data_train.max(), 1000)
X2 = np.linspace(data_valid.min(), data_valid.max(), 1000)
fig, ax = plt.subplots(1,2, figsize=(12,6))
ax[0].plot(X1, displot_dataTest.kde.pdf(X1), label='train')
ax[1].plot(X2, displot_dataValid.kde.pdf(X1), label='valid')
The plotting of the histograms and kde-functions inside one plot works without problems. Now I would like to have the 2 kde-functions inside one plot but when using the posted code, I get the following error AttributeError: 'FacetGrid' object has no attribute 'kde'
Do you have any idea, how I can combined the 2 kde-functions inside one plot (without the histogram)?
sns.displot() returns a FacetGrid. That doesn't work as input for ax.plot(). Also, displot_dataTest.kde.pdf is never valid. However, you can write sns.kdeplot(data=data_train, ax=ax[0]) to create a kdeplot inside the first subplot. See the docs; note the optional parameters cut= and clip= that can be used to adjust the limits.
If you only want one subplot, you can use fig, ax = plt.subplots(1, 1, figsize=(12,6)) and use ax=ax instead of ax=ax[0] as in that case ax is just a single subplot, not an array of subplots.
The following code has been tested using the latest seaborn version:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig, ax = plt.subplots(figsize=(12, 6))
sns.kdeplot(data=np.random.normal(0.1, 1, 100).cumsum(),
color='crimson', label='train', fill=True, ax=ax)
sns.kdeplot(data=np.random.normal(0.1, 1, 100).cumsum(),
color='limegreen', label='valid', fill=True, ax=ax)
ax.legend()
plt.tight_layout()
plt.show()

Add multiples graphs in one figure

I'm learning Python using Jupiter and I'm struggling trying to put the graphs into one figure. Here's what I have so far...
Code for my graphs(I have three of graphs, they only differ in color and lines vs. dot):
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
one = plt.figure()
plt.plot(x_v, y_v, '#008000') #change color using hex strings
plt.xlabel('x')
plt.ylabel('y')
plt.show()
two = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
plt.show()
three = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
plt.show()
Here's code that I have so far to make it one figure... I was wondering If I should should put it in a np.arange and plot it, but I can't seem to get it to work....
def f(x):
return one
def g(x):
return two
def h(x):
return three
If anyone can help, it'll be of great use! Thank you!
You can use plt.subplots:
fig, (ax1, ax2, ax3) = plt.subplots(figsize=(15, 5), ncols=3)
ax1.plot(x_v, y_v, '#008000')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax2.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
ax3.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
Here is one way to approach multiple plots with plt.subplots. I think it is very easy to follow and also gives a lot of control over individual plots:
import numpy as np
import matplotlib.pyplot as plt
#generating test data
x = np.arange(0,9)
y = np.arange(1,10)
#defining figure layout (i.e. rows, columns, size, horizontal and vertical space between subplots
fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(15,7))
plt.subplots_adjust(hspace=0.4,wspace=0.2)
#first subplot (numbering can be read as 1st plot in a grid of 2x2)
plt.subplot(2,2,1)
plt.plot(x,y)
#second subplot in a grid of 2x2
plt.subplot(2,2,2)
plt.plot(x,y,ls='--')
#third subplot in a grid of 2x2
plt.subplot(2,2,3)
plt.scatter(x,y)
#fourth subplot in a grid of 2x2
plt.subplot(2,2,4)
plt.plot(x,y)
plt.tight_layout()
plt.show()
Output:

Is there a way to replace a matplotlib subplot with a legend (rather than have the legend outside the subplots)?

I have a figure with 11 scatter plots as subplots. I would like the legend (same across all 11 subplots) to replace the 12th subplot. Is there a way to put the legend there and have it be the same size as the subplots?
Matplotlib scatter plot of 11 subplots
Sort of a manual approach, but here it is:
You can "remove" an axis using ax.clear() and ax.set_axis_off(). Then you can create patches with specific colors and labels, and create a legend in the desired ax based on them.
Try this:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
# Create figure with subplots
fig, axes = plt.subplots(figsize=(16, 16), ncols=4, nrows=3, sharex=True, sharey=True)
# Plot some random data
for row in axes:
for ax in row:
ax.scatter(np.random.random(5), np.random.random(5), color='green')
ax.scatter(np.random.random(2), np.random.random(2), color='red')
ax.scatter(np.random.random(3), np.random.random(3), color='orange')
ax.set_title('some title')
# Clear bottom-right ax
bottom_right_ax = axes[-1][-1]
bottom_right_ax.clear() # clears the random data I plotted previously
bottom_right_ax.set_axis_off() # removes the XY axes
# Manually create legend handles (patches)
red_patch = mpatches.Patch(color='red', label='Red data')
green_patch = mpatches.Patch(color='green', label='Green data')
orange_patch = mpatches.Patch(color='orange', label='Orange data')
# Add legend to bottom-right ax
bottom_right_ax.legend(handles=[red_patch, green_patch, orange_patch], loc='center')
# Show figure
plt.show()
Output:

How to avoid negative numbers on axis in matplotlib scatterplot

I am doing a simple scatterplot using Pythons scatterplot. But no matter how I set my axis, and no matter that I don't have any negative values I get negative values at the x-axis. How do I force the axis to start at 0?
My code:
fig, ax = plt.subplots(1)
ax.scatter(lengths,breadths, alpha=0.3, color="#e74c3c", edgecolors='none')
spines_to_remove = ['top', 'right']
for spine in spines_to_remove:
ax.spines[spine].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_view_interval(0,400)
ax.yaxis.set_view_interval(0,90)
figname = 'scatterlengthsbreadths.pdf'
fig.savefig(figname, bbox_inches='tight')
You can use ax.set_xlim(lower_limit, upper_limit) to choose your x-limits. Note that there is a similar command ax.set_ylim for the y-limits.
Note that if you're just using the pyplot interface, i.e. without using fig and ax, then the command is plt.xlim().
For example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [4,5,6]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
plt.show()

Creating sparklines using matplotlib in python

I am working on matplotlib and created some graphs like bar chart, bubble chart and others.
Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ?
for example with the following code
import matplotlib.pyplot as plt
import numpy as np
x=[1,2,3,4,5]
y=[5,7,2,6,2]
plt.plot(x, y)
plt.show()
the line graph generated is the following:
But I couldn't get what is the difference between a line chart and a spark lien chart for the same data. Please help me understand
A sparkline is the same as a line plot but without axes or coordinates. They can be used to show the "shape" of the data in a compact way.
You can cram several line plots in the same figure just by using subplots and changing properties of the resulting Axes for each subplot:
data = np.cumsum(np.random.rand(1000)-0.5)
data = data - np.mean(data)
fig = plt.figure()
ax1 = fig.add_subplot(411) # nrows, ncols, plot_number, top sparkline
ax1.plot(data, 'b-')
ax1.axhline(c='grey', alpha=0.5)
ax2 = fig.add_subplot(412, sharex=ax1)
ax2.plot(data, 'g-')
ax2.axhline(c='grey', alpha=0.5)
ax3 = fig.add_subplot(413, sharex=ax1)
ax3.plot(data, 'y-')
ax3.axhline(c='grey', alpha=0.5)
ax4 = fig.add_subplot(414, sharex=ax1) # bottom sparkline
ax4.plot(data, 'r-')
ax4.axhline(c='grey', alpha=0.5)
for axes in [ax1, ax2, ax3, ax4]: # remove all borders
plt.setp(axes.get_xticklabels(), visible=False)
plt.setp(axes.get_yticklabels(), visible=False)
plt.setp(axes.get_xticklines(), visible=False)
plt.setp(axes.get_yticklines(), visible=False)
plt.setp(axes.spines.values(), visible=False)
# bottom sparkline
plt.setp(ax4.get_xticklabels(), visible=True)
plt.setp(ax4.get_xticklines(), visible=True)
ax4.xaxis.tick_bottom() # but onlyt the lower x ticks not x ticks at the top
plt.tight_layout()
plt.show()
A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# create some random data
x = np.cumsum(np.random.rand(1000)-0.5)
# plot it
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k')
plt.plot(len(x)-1, x[-1], color='r', marker='o')
# remove all the axes
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
#show it
plt.show()

Categories

Resources