I want to display yaxis on both side. In matplotlib 1.2, I can use following code:
ax.tick_params(labelright = True)
However, there is no method tick_params for Axes in matplotlib 0.99. Is there any simple way to do this in 0.99?
Tks
EDIT
I got this solution followed by #Brian Cain's
ax2 = ax1.twinx()
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([t.get_text() for t in ax1.get_yticklabels()])
Here is an example from matplotlib docs with differing scales on each Y axis. You could use the same scale if you preferred.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()
Related
I would like to show the topmost minor gridline (at 2.25) in its full width without adjusting the limits manually. How can I achieve this?
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots(constrained_layout=True)
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.25)
plt.show()
Adjusting edge gridline visibility in matplotlib
There are a couple ways to accomplish what you're looking for. I think the best method would be to hide the top and right spines. Alternatively, ax.grid takes Line2D args which includes clip_on. Setting clip_on=False has the intended effect of making the ax box not clip the line - but it does result in the top spine going through the grid line (which is not very attractive in my opinion). Lastly, as you mention, you could make a minor increase in y lim (to 2.26 or 2.27) and that would also make the top grid line more visible.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,12))
axes = axes.flatten()
ax = axes[0]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', clip_on=False)
[ax.spines[s].set_visible(False) for s in ['top', 'right']]
ax.set_ylim(0, 2.25)
ax.set_title('Hide top/right spines', fontsize=16, fontweight='bold')
ax = axes[1]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', zorder=3, clip_on=False)
ax.set_ylim(0, 2.25)
ax.set_title('Make clip_on=False', fontsize=16, fontweight='bold')
ax = axes[2]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.265)
ax.set_title('Increase ylim to 2.265', fontsize=16, fontweight='bold')
axes[3].axis('off')
I am using secondary y-axis and cmap color but when I plot together the color bar cross to my plot
here is my code
fig,ax1=plt.subplots()
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10,60), c='Lifetime1 (a)', colormap='jet_r', vmin=0, vmax=25, ax=ax1)
graph.axhline(0, color='k')
plt.xticks(rotation=90)
ax2 = ax1.twinx()
ax2.plot(df_Combine_min_select1["CumEnergy1 (kWH)"])
plt.show()
and here is my plotting
anyone can help how to solve this issue?
Thank you
When you let pandas automatically create a colorbar, you don't have positioning options. Therefore, you can create the colorbar in a separate step and provide the pad= parameter to set a wider gap. Default, pad is 0.05, meaning 5% of the width of the subplot.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
df_Combine = pd.DataFrame({'Parameter2': np.random.rand(10) * 10,
'NPV (MM €)': np.random.rand(10),
'Lifetime1 (a)': np.random.rand(10) * 25,
})
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10, 60), c='Lifetime1 (a)',
colormap='jet_r', vmin=0, vmax=25, ax=ax1, colorbar=False)
plt.colorbar(ax1.collections[0], ax=ax1, pad=0.1)
ax2 = ax1.twinx()
ax2.plot(np.random.rand(10))
plt.show()
How can I solve this? I want to do 4 subplots with matplotlib, I have used the subplot option but the result is just a big plot. I don't have idea what is the problem. I want to see four subplots, each one with title, and a suptitle for them.
I don't have idea how can I solve it?
Can you help me please to fix it?
Thanks a lot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from matplotlib.collections import LineCollection
import matplotlib.patches as mpatches
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as tkr
from pylab import text
with open("file1.txt") as f:
m1 = map(float,f)
with open ("file2.txt") as f:
m2 = map(float, f)
fig, ax = plt.subplots(sharey='row')
fig.set_figwidth(18) #Width figure
fig.set_figheight(12) #Height figure
plt.rcParams['figure.dpi'] = 300
plt.subplots_adjust(wspace=0.18, hspace=0.2)
fig.suptitle('PLOTS', y=0.93, fontsize=15)
# Plot
plt.subplot(421)
y = np.array(m1)
x = np.arange(len(y))
threshold = 0.5
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)
linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'
for y_ in segments_y]
segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,268)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(x), max(x)+1, 10))
plt.grid()
plt.tight_layout()
# Plot
plt.subplot(423)
p = np.array(m2)
o = np.arange(len(p))
threshold = 0.5
segments_o = np.r_[o[0], o[1:-1].repeat(2), o[-1]].reshape(-1, 2)
segments_p = np.r_[p[0], p[1:-1].repeat(2), p[-1]].reshape(-1, 2)
linecolors = ['red' if p_[0] > threshold and p_[1] > threshold else 'blue'
for p_ in segments_p]
segments = [zip(o_, p_) for o_, p_ in zip(segments_o, segments_p)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,383)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(o), max(o)+1, 10))
plt.grid()
plt.tight_layout()
plt.show()
#plt.savefig('figure.png', format='png', bbox_inches="tight", dpi=300)
How can I solve this?
where is the problem?
You need to specify the number of plots you want to be created by matplotlib.pyplot.subplots,
nrows = 2
ncols = 2
fig, ax = plt.subplots(nrows, ncols, sharey='row')
which will create an array of axes instances with shape (nrows, ncols). You can then plot to individual axes via
ax[0,0].plot(...)
Although in order to set tick properties, labels, etc for the axes you need to use the axes versions of the functions instead of the pyplot versions. I.e.
ax[0, 0].set_xticks(...)
# instead of
plt.xticks(...)
ax[0, 0].set_title(...)
# instead of
plt.title(...)
ax[0, 0].set_xlabel(...)
# instead of
plt.set_xlabel(...)
In pyplot, you can change the order of different graphs using the zorder option or by changing the order of the plot() commands. However, when you add an alternative axis via ax2 = twinx(), the new axis will always overlay the old axis (as described in the documentation).
Is it possible to change the order of the axis to move the alternative (twinned) y-axis to background?
In the example below, I would like to display the blue line on top of the histogram:
import numpy as np
import matplotlib.pyplot as plt
import random
# Data
x = np.arange(-3.0, 3.01, 0.1)
y = np.power(x,2)
y2 = 1/np.sqrt(2*np.pi) * np.exp(-y/2)
data = [random.gauss(0.0, 1.0) for i in range(1000)]
# Plot figure
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax2.hist(data, bins=40, normed=True, color='g',zorder=0)
ax2.plot(x, y2, color='r', linewidth=2, zorder=2)
ax1.plot(x, y, color='b', linewidth=2, zorder=5)
ax1.set_ylabel("Parabola")
ax2.set_ylabel("Normal distribution")
ax1.yaxis.label.set_color('b')
ax2.yaxis.label.set_color('r')
plt.show()
Edit: For some reason, I am unable to upload the image generated by this code. I will try again later.
You can set the zorder of an axes, ax.set_zorder(). One would then need to remove the background of that axes, such that the axes below is still visible.
ax2 = ax1.twinx()
ax1.set_zorder(10)
ax1.patch.set_visible(False)
I plot using two y-axis, on the left and the right of a matplotlib figure and use zorder to control the position of the plots. I need to define the zorder across axes in the same figure.
Problem
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, np.sin(x), color='red', linewidth=10, zorder=1 )
ax2 = ax1.twinx()
ax2.plot( x, x, color='blue', linewidth=10, zorder=-1)
In the previous diagram, I would expect the blue line to appear behind the red plot.
How do I control the zorder when using twin axes?
I am using:
python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1
This should work
ax1.set_zorder(ax2.get_zorder()+1)
ax1.patch.set_visible(False)
the following codes works
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
x = np.arange(-10,10,0.01)
plt.figure(figsize=(10, 5))
fig = plt.subplot(111)
"""be attention to here. it's fig.plot, not ax1.plot
if you write ax1.plot, then it does not work.
"""
fig.plot(x, x, color ='blue', linewidth =10)
ax2 = fig.twinx()
ax2.plot(x, np.sin(x), color='red', linewidth =10)
"""
It looks like the two axes have separate z-stacks.
The axes are z-ordered with the most recent axis on top
"""
fig.set_zorder(ax2.get_zorder()+1)
fig.patch.set_visible(False)
plt.show()
It looks like the two axes have separate z-stacks. The axes are z-ordered with the most recent axis on top, so you need to move the curve you want on top to the last axis you create:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, x, color='blue', linewidth=10 )
ax2 = ax1.twinx()
ax2.plot( x, np.sin(x), color='red', linewidth=10 )