Plotting grids across the subplots Python matplotlib - python

I have tried the following:
d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig = plt.figure()
fig.set_size_inches(30,10)
ax1 = fig.add_subplot(211)
line1 = ax1.plot(d,marker='.',color='b',label="1 row")
ax2 = fig.add_subplot(212)
line1 = ax2.plot(f,marker='.',color='b',label="1 row")
ax1.grid()
ax2.grid()
plt.show()
I got the following output :
But I was expecting the following output:
How I can get the grids across the two plots?

There is no built-in option to create inter-subplot grids. In this case I'd say an easy option is to create a third axes in the background with the same grid in x direction, such that the gridline can be seen in between the two subplots.
import matplotlib.pyplot as plt
d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True)
ax3 = fig.add_subplot(111, zorder=-1)
for _, spine in ax3.spines.items():
spine.set_visible(False)
ax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False )
ax3.get_shared_x_axes().join(ax3,ax1)
ax3.grid(axis="x")
line1 = ax1.plot(d, marker='.', color='b', label="1 row")
line1 = ax2.plot(f, marker='.', color='b', label="1 row")
ax1.grid()
ax2.grid()
plt.show()

Here is my solution:
import matplotlib.pyplot as plt
x1 = [1,2,3,4,5,6,7,8,9]
x2= [0,1,0,0,1,0,1,1,0]
x3= range(-10,0)
# frameon=False removes frames
# fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True, subplot_kw=dict(frameon=False))
fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()
ax3.grid()
ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)
Without frames subplot_kw=dict(frameon=False):

An option is to create a single plot then just offset the data. So one set plots above the other.

Related

Ghost plot being generated

I have the following code:
fig = plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
ax2 = ax1.twinx()
num = list111.lt(-90).sum(1)
plt.yticks(fontsize = 25)
ax = num.plot(figsize=(45,25), ax=ax2, color = 'Red')
df2.plot(y = 'Close', figsize=(45,25), ax=ax1, color = 'Green')
ax1.grid()
ax.margins(x=0)
I am trying to plot ax1 and ax2 in the same graph. What i am getting is a ghost plot:
How can i get rid of the second ghost plot and move the x axis with label to the top plot?
The statement
ax2 = plt.subplot(212, sharex = ax1)
generates a subplot located beneath the ax1 subplot. But it is in contradiction with the statement
ax2 = ax1.twinx()
which points towards a secondary y-axis on the ax1 axes.
If you want all the data to be plotted only on a single axes, you can delete the first statement and use the .twinx() method:
ax1 = plt.axes()
ax2 = ax1.twinx()
# remaining code
otherwise, use both axes separately with
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
# remaining code

matplotlib: How to remove ticks&tick values from secondary axis?

I have this code for a graph, and I do not want the values & ticks on the top and right axes.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2 = ax.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax2 = ax.secondary_yaxis('right')
ax2.set_ylabel('SAD')
#Remove ticks/values
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_yticks([])
ax.set_xticks([])
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.set_yticks([])
ax2.set_xticks([])
#Show graph
plt.show()
it's showing it like this: image of graph
Use tick_params to manipulate the axis ticks and labels:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
#Set axis labels
ax1.set_xlabel('NEGATIVE')
ax1.set_ylabel('HAPPY')
ax2 = ax1.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax3 = ax1.secondary_yaxis('right')
ax3.set_ylabel('SAD')
#Remove ticks/values
for ax in (ax1, ax2, ax3):
ax.tick_params(left=False, labelleft=False, top=False, labeltop=False,
right=False, labelright=False, bottom=False, labelbottom=False)
#Show graph
plt.show()
A comment asked for how to only turn top and left ticks and labels off. This would be
for ax in (ax1, ax2, ax3):
ax.tick_params(top=False, labeltop=False, right=False, labelright=False)
Interesting why SecondaryAxis doesn't accept tick params, however let's use twinx and twiny:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#Set axis labels
ax.set_xlabel('NEGATIVE')
ax.set_ylabel('HAPPY')
ax2x = ax.twiny()
ax2.set_yticks([])
ax2x.set_xlabel('POSITIVE')
ax2y = ax.twinx()
ax2y.set_ylabel('SAD')
ax2x.set_xticks([])
ax2y.set_yticks([])
#Show graph
plt.show()
Output:

How to plot sublots when creating plots in a for loop in python?

I'm new to programming and currently stuck on this: I create 4 different plots using a for loop and I want to assign each plot to a different subplot. Basically, I want 4 plots in a 2x2 grid so I can compare my data. Anyone knows how I can achieve this? My approach was to create a list of subplots and then assign every plot to a subplot using a nested plot:
import matplotlib.pyplot as plt
import numpy as np
def load_file(filename):
return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax_list=[ax1, ax2, ax3, ax4]
for i,filename in enumerate(file_list):
for p in ax_list:
x,y = load_file(filename)
plt.plot(x,y,
label=l, #I assign labels from a list beforehand, as well as colors
color=c,
linewidth=0.5,
ls='-',
)
p.plot()
The problem is, all plots are assigned to only one subplot and I don't know how to correct this. I'd appreciate any help!
I guess what you want is to show different data on all 4 plots, hence use a single loop. Make sure to use the axes plotting method, not plt.plot as the latter would always plot in the last subplot.
import matplotlib.pyplot as plt
import numpy as np
def load_file(filename):
return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)
fig, ax_list = plt.subplots(2,2)
for i,(filename,ax) in enumerate(zip(file_list, ax_list.flatten())):
x,y = load_file(filename)
ax.plot(x,y, linewidth=0.5,ls='-' )
plt.show()
You don't need to loop over filenames and plots, only need to select the next plot in the list.
for i, filename in enumerate(file_list):
p = ax_list[i]:
x,y = load_file(filename)
p.plot(x, y,
label=l, #I assign labels from a list beforehand, as well as colors
color=c,
linewidth=0.5,
ls='-')
plt.plot()
You can also replace
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax_list=[ax1, ax2, ax3, ax4]
with just
fig, ax_list = plt.subplots(2, 2)
ax_list = ax_list.flatten()
To get a simple 2x2 grid.

Pandas: plotting two histograms on the same plot

I would like to have 2 histograms to appear on the same plot (with different colors, and possibly differente alphas). I tried
import random
x = pd.DataFrame([random.gauss(3,1) for _ in range(400)])
y = pd.DataFrame([random.gauss(4,2) for _ in range(400)])
x.hist( alpha=0.5, label='x')
y.hist(alpha=0.5, label='y')
x.plot(kind='kde', style='k--')
y.plot(kind='kde', style='k--')
plt.legend(loc='upper right')
plt.show()
This produces the result in 4 different plots. How can I have them on the same one?
If I understood correctly, both hists should go into the same subplot. So it should be
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)
You can also pass the pandas plot method an axis object, so if you want both kde's in another plot do:
fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='kde', ax=ax)
y.plot(kind='kde', ax=ax, color='red')
To get everything into a single plot you need two different y-scales since kde is density and histogram is frequency. For that you use the axes.twinx() command.
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)
ax1 = ax.twinx()
x.plot(kind='kde', ax=ax1)
y.plot(kind='kde', ax=ax1, color='red')
You can use plt.figure() and the function add_subplot(): the first 2 arguments are the number of rows and cols you want in your plot, the last is the position of the subplot in the plot.
fig = plt.figure()
subplot = fig.add_subplot(1, 2, 1)
subplot.hist(x.ix[:,0], alpha=0.5)
subplot = fig.add_subplot(1, 2, 2)
subplot.hist(y.ix[:,0], alpha=0.5)

How to add a title to each subplot

I have one figure which contains many subplots.
fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')
# Returns the Axes instance
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
How do I add titles to the subplots?
fig.suptitle adds a title to all graphs and although ax.set_title() exists, the latter does not add any title to my subplots.
Thank you for your help.
Edit:
Corrected typo about set_title(). Thanks Rutger Kassies
ax.title.set_text('My Plot Title') seems to work too.
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
ax.set_title() should set the titles for separate subplots:
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)
ax = plt.subplot("212")
ax.set_title("Title for second plot")
ax.plot(data)
plt.show()
Can you check if this code works for you? Maybe something overwrites them later?
A shorthand answer assuming
import matplotlib.pyplot as plt:
plt.gca().set_title('title')
as in:
plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...
Then there is no need for superfluous variables.
If you want to make it shorter, you could write :
import matplotlib.pyplot as plt
for i in range(4):
plt.subplot(2,2,i+1).set_title(f'Subplot n°{i+1}')
plt.show()
It makes it maybe less clear but you don't need more lines or variables
A solution I tend to use more and more is this one:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 1
for i, ax in enumerate(axs.ravel()): # 2
ax.set_title("Plot #{}".format(i)) # 3
Create your arbitrary number of axes
axs.ravel() converts your 2-dim object to a 1-dim vector in row-major style
assigns the title to the current axis-object
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4,figsize=(11, 7))
grid = plt.GridSpec(2, 2, wspace=0.2, hspace=0.5)
ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1:])
ax3 = plt.subplot(grid[1, :1])
ax4 = plt.subplot(grid[1, 1:])
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.
The catch is you can define dynamic axes(ax) as in Line 1 of code
and you can set its title inside a loop.
The rows of 2D array is length (len) of axis(ax)
Each row has 2 items i.e. It is list within a list (Point No.2)
set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
for i in range(len(ax)):
for j in range(len(ax[i])):
## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
ax[i,j].set_title('Title-' + str(i) + str(j))
You are able to give every graph a different title and label by Iteration only.
titles = {221: 'First Plot', 222: 'Second Plot', 223: 'Third Plot', 224: 'Fourth Plot'}
fig = plt.figure()
for x in range(221,225):
ax = fig.add_subplot(x)
ax.title.set_text(titles.get(x))
plt.subplots_adjust(left=0.1,
bottom=0.1,
right=0.9,
top=0.9,
wspace=0.4,
hspace=0.4)
plt.show()
Output:
As of matplotlib 3.4.3, the Figure.add_subplot function supports kwargs with title as:
fig.add_subplot(311, title="first")
fig.add_subplot(312, title="second")
For completeness, the requested result can also be achieve without explicit reference to the figure axes as follows:
import matplotlib.pyplot as plt
plt.subplot(221)
plt.title("Title 1")
plt.subplot(222)
plt.title("Title 2")
plt.subplot(223)
plt.title("Title 3")
plt.subplot(224)
plt.title("Title 4")
Use plt.tight_layout() after the last plot if you have issues with overlapping labels.

Categories