Hello I'm looking for a way to turn off the exponent on an matplot figure. Is there an easy way to turn that off?
I'm also looking for a possibility get that exponent value. I tried already
ax1.yaxis.get_offset_text().get_text()
But that only results in a string with latex format. And I'd prefer to have a float.
In the end I'd like to have an easy possibility to position the Exponent anywhere on the plot.
I hope that concludes what I'm looking for.
Thank you for your help in advance :)
edit:
Some more code:
fig = plt.figure(figsize = size)
gs = gridspec.GridSpec(1,2)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)
ax1.tick_params(direction='in',labelsize=fontsize)
ax2.tick_params(direction='in',labelsize=fontsize)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position("right")
ax1.set_ylabel('Intensität / willk. Einh.')
ax1.set_xlabel('Messpunkt')
ax2.set_xlabel('Messpunkt')
test = ax1.yaxis.get_offset_text().get_text()
ax1.plot([],[], linestyle = 'None',label = test + name + r' bei $p_0 =\,$'+ str(pressure[0]) + r'$\,$ mbar')
ax2.plot([],[], linestyle = 'None',label = name + r' bei $p_0 =\,$'+ str(pressure[1])+ r'$\,$ mbar')
plt.setp([ax1, ax2], visible = True)
gs.tight_layout(fig)
y0 = file(Messung['Pfad'][key[0]],Messung['Name'][key[0]])
y1 = file(Messung['Pfad'][key[1]],Messung['Name'][key[1]])
x = np.arange(0,len(y0),1)
ax1.plot(x,y1, 's', label = 'Messpunkt', markersize = 3, color = colors(T0))
ax2.plot(x,y0 , 's', label = 'Messpunkt', markersize = 3, color = colors(T0))
#format_label_string_with_exponent(ax1, axis='both')
#format_label_string_with_exponent(ax2, axis='both')
ax1.legend(bbox_to_anchor=(0.3, 1, 0, 0.08), loc=1, ncol= 2, mode="expand",borderaxespad=0.5,frameon=False, fontsize = fontsize)
ax2.legend(bbox_to_anchor=(0.3, 1, 0, 0.08), loc=1, ncol= 2, mode="expand",borderaxespad=0.5,frameon=False, fontsize = fontsize)
plt.show()
I found a way to turn the exponent off, in case someone is looking for that:
ax.yaxis.offsetText.set_visible(False)
ax is the name of the axis and its possible to turn it separately on or off x and y axis
Related
Why doesn't zorder work in this case? I've tried using it but the text still ends up being covered by the bar plot towers.
import numpy as np
from matplotlib import pyplot as plt
Percentage_Differences_1 = np.array([ [7.94*(10**-10),7.94*(10**-9),7.94*(10**-8),7.94*(10**-7),7.94*(10**-6),7.94*(10**-5)],
[7.92*(10**-12),7.92*(10**-11),7.92*(10**-10),7.92*(10**-9),7.92*(10**-8),7.92*(10**-7)],
[7.72*(10**-14),7.72*(10**-13),7.72*(10**-12),7.72*(10**-11),7.72*(10**-10),7.72*(10**-9)],
[5.66*(10**-16),5.66*(10**-15),5.66*(10**-14),5.66*(10**-13),5.66*(10**-12),5.66*(10**-11)],
[1.49*(10**-17),1.49*(10**-16),1.49*(10**-15),1.49*(10**-14),1.49*(10**-13),1.49*(10**-12)],
[2.21*(10**-18),2.21*(10**-17),2.21*(10**-16),2.21*(10**-15),2.21*(10**-14),2.21*(10**-13)] ]) # Layer 1, 12
fig1 = plt.figure(dpi = 120, tight_layout = True)
fig1.set_size_inches(10, 7)
ax1 = fig1.add_subplot(111, projection='3d')
width = depth = 0.3
column_names = ['$10^{-6} m$','$10^{-5} m$','$10^{-4} m$','$10^{-3} m$','$10^{-2} m$','$10^{-1} m$']
row_names = ['$10^{-6} g$','$10^{-5} g$','$10^{-4} g$','$10^{-3} g$','$10^{-2} g$','$10^{-1} g$']
height_names = ['$10^{-2}$','$10^{-4}$','$10^{-6}$','$10^{-8}$','$10^{-10}$','$10^{-12}$','$10^{-14}$','$10^{-16}$','$10^{-18}$']
for x in range(0,6):
for y in range(0,6):
plot1 = ax1.bar3d(x, y, 0, width, depth, np.log10(Percentage_Differences_1[x][y]), color = "#0040bf", alpha=0.3, zorder = 1)
txt1 = ax1.text(x,y,1.15*np.log10(Percentage_Differences_1[x][y]),'{:.2e}'.format(Percentage_Differences_1[y][x]), verticalalignment='top', bbox=dict(facecolor='grey', alpha=0.5), zorder = 2)
ax1.view_init(-140, -30)
ax1.set_xticks(np.linspace(0, 6, num = 6))
ax1.set_yticks(np.linspace(0, 6, num = 6))
ax1.set_xticklabels(column_names)
ax1.set_yticklabels(row_names)
ax1.set_zticklabels(height_names)
ax1.set_xlabel("Mass", labelpad = 13, rotation = 45)
ax1.set_ylabel("Radius", labelpad = 10, rotation = 45)
ax1.set_zlabel("Deviation $\Delta$")
ax1.set_title("1st Initial Condition: $r(0)$ and $r'(0)$ of $\Theta(12) = 2.18 \\times 10^{7} m$", pad = 40)
plt.show()
I've tried using both set_zorder and zorder but the plot still ends up covering the majority of the text labels.
Change your zorder for a number larger than the number of bar objects, 100 for example:
I've got two pandas series I would like to plot on the same axis, using a twinx. Here is a picture of what it looks like:
fig,(ax1,ax2,ax3,ax4,ax5) = plt.subplots(nrows = 5,ncols = 1, figsize = (8,13))
plt.subplots_adjust(hspace = 0.5)
ax1_1 = ax1.twinx()
df[["Var"]].plot(ax = ax1, label = 'Variance')
df[['w2']].plot(ax = ax1_1, color = 'g', label = '$w$')
ax1.locator_params('y',nbins = 5)
ax1_1.locator_params('y', nbins = 5)
ax1.set_ylabel('AC', labelpad = 10)
ax1_1.set_ylabel('w', labelpad = 10)
ax1.legend(loc = 'upper left')
ax1_1.legend()
I'd like to edit the x axis ticks, but using ax1.set_xticks() and ax1.set_xticklabels() doesn't seem to work. Furthermore, why are there are no x ticks after I execute the code found above? Shouldn't the ticks be the index of the Series?
Community,
Say I have created a scatter plot with Python's matplotlib:
plt.scatter(x, y)
Let's say this is the data:
Now, is there a way to add colored boxes on the axis (between given x-values, e.g.,: add a green box from x=-0.2 to x=0, add a ...) like this:
Including the text labels (at the mid-range I guess).
I am not even sure how to get started on this one to be honest (besides making the scatter plot).
Question
Can anyone at least direct me to a feature of matplotlib that does this (or any other Python package)?
Your help is much appreciated.
You probably want to go with matplotlib's text()
function. Maybe something like this,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi * x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')
ax.set_xlim(-0.2, 1.2)
ax.set_ylim(-1.5, 1.5)
x_ticks = ax.get_xticks()
y_ticks = ax.get_yticks()
# use len(x_ticks)-1 number of colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'orange']
for i, x_tick in enumerate(x_ticks[:-1]):
ax.text(x_tick+0.03, y_ticks[0]-0.165, "text %i"%i,
bbox={'fc':colors[i], 'pad':10})
This code returns this image. You can adjust the padding and x,y position as necessary to achieve the exact look you're going for.
fig = plt.figure(figsize=(6,4))
plt.plot(np.arange(0,7,1),np.arange(0,7,1),linestyle='--', marker='o', color='b')
rect1 = plt.Rectangle((1.5,1.5),(0.7),(0.5), facecolor="grey",edgecolor="black",alpha=0.8)
rect2 = plt.Rectangle((2.5,2.5),(0.7),(0.5), facecolor="yellow",edgecolor="black",alpha=0.8)
rect3 = plt.Rectangle((3.5,3.5),(0.7),(0.5), facecolor="k",edgecolor="black",alpha=0.8)
plt.gca().add_patch(rect1)
plt.gca().add_patch(rect2)
plt.gca().add_patch(rect3)
plt.text(1.65,1.65,r"Grey",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(2.55,2.65,r"Yellow",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(3.555,3.65,r"Black",fontsize = 10,zorder = 5,color = 'white',fontweight = 'bold')
I would like to set legend and text boxes locations and styles exactly same, the latter especially to make text aligned.
import matplotlib.pyplot as plt
x = np.arange(10)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(3):
ax.plot(x, i * x ** 2, label = '$y = %i x^2$'%i)
ax.set_title('example plot')
# Shrink the axis by 20% to put legend and text at the bottom
#+ of the figure
vspace = .2
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * vspace,
box.width, box.height * (1 - vspace)])
# Put a legend to the bottom left of the current axis
x, y = 0, 0
# First solution
leg = ax.legend(loc = 'lower left', bbox_to_anchor = (x, y), \
bbox_transform = plt.gcf().transFigure)
# Second solution
#leg = ax.legend(loc = (x, y)) , bbox_transform = plt.gcf().transFigure)
# getting the legend location and size properties using a code line I found
#+ somewhere in SoF
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)
ax.text(x + bb.width, y, 'some text', transform = plt.gcf().transFigure, \
bbox = dict(boxstyle = 'square', ec = (0, 0, 0), fc = (1, 1, 1)))
plt.show()
This should place the text at the right of the legend box but that's not what it does. And the two boxes are not vertically aligned.
The second solution does not actually anchoring the legend to the figure, but to the axes instead.
You can use the frame data to get the right width in order to position the Text() object correctly.
In the example below I had to apply a 1.1 factor for the width (this value I haven't found how to get, and if you don't apply the factor the text clashes with the legend).
Note also that you must plt.draw() before getting the right width value.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure(figsize=(3, 2))
ax = fig.add_subplot(1, 1, 1)
for i in range(3):
ax.plot(x, i*x**2, label=r'$y = %i \cdot x^2$'%i)
ax.set_title('example plot')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
x, y = 0.2, 0.5
leg = ax.legend(loc='lower left', bbox_to_anchor=(x, y),
bbox_transform=fig.transFigure, fontsize=8)
plt.draw()
f = leg.get_frame()
w0, h0 = f.get_width(), f.get_height()
inv = fig.transFigure.inverted()
w, h = inv.transform((w0, h0))
ax.text(x+w*1.1, y+h/2., 'some text', transform=fig.transFigure,
bbox=dict(boxstyle='square', ec=(0, 0, 0), fc=(1, 1, 1)),
fontsize=7)
fig.savefig('test.jpg', bbox_inches='tight')
for x, y = 0.2, 0.5:
for x, y = -0.3, -0.3:
I have two figures with 3 subplots in each of them. In each subplot, there are 20 different curves, which represents 20 steps, by using a for loop. How can I make the color of the curves gradually fade? Like in the code I have below, the top subplot (311) has 20 blue curves...how can I make the 1st step be dark blue and have the blue gradually fade until the last step be a light blue? Also, how do I make the two figures pop up on screen at once? Right now, I have to manually close the first figure in order for the second figure to pop up.
from pylab import *
for raw_step in raw:
raw_step = zip(*raw_step)
Raw_Vertex, Raw_KI, Raw_KII, Raw_KIII = raw_step[0], raw_step[1], raw_step[2], raw_step[3]
subplot(311)
plot(Raw_Vertex, Raw_KI, 'bo-')
grid(True)
title('Raw SIFs')
ylabel('K_I')
subplot(312)
plot(Raw_Vertex, Raw_KII, 'go-')
grid(True)
ylabel('K_II')
subplot(313)
plot(Raw_Vertex, Raw_KIII, 'ro-')
grid(True)
xlabel('Vertex')
ylabel('K_III')
show()
for mls_step in mls:
mls_step = zip(*mls_step)
MLS_Vertex, MLS_KI, MLS_KII, MLS_KIII = mls_step[0], mls_step[1], mls_step[2], mls_step[3]
subplot(311)
plot(MLS_Vertex, MLS_KI, 'bo-')
grid(True)
title('MLS SIFs')
ylabel('K_I')
subplot(312)
plot(MLS_Vertex, MLS_KII, 'go-')
grid(True)
ylabel('K_II')
subplot(313)
plot(MLS_Vertex, MLS_KIII, 'ro-')
grid(True)
xlabel('Vertex')
ylabel('K_III')
show()
To get lightening shades of blue, use
blues = plt.get_cmap('Blues') # this returns a colormap
color = blues(1 - float(i)/(len(raw)-1)) # blues(x) returns a color for each x between 0.0 and 1.0
To place the subplots side-by-side, use fig.add_subplots(row, columns, n) to define the 6 axes.
fig = plt.figure()
ax[1] = fig.add_subplot(3, 2, 1) # 3x2 grid, 1st plot
...
ax[6] = fig.add_subplot(3, 2, 6) # 3x2 grid, 6th plot
import matplotlib.pyplot as plt
import numpy as np
raw = range(20)
mls = range(20)
ax = {}
blues = plt.get_cmap('Blues')
reds = plt.get_cmap('Reds')
greens = plt.get_cmap('Greens')
fig = plt.figure()
ax[1] = fig.add_subplot(3, 2, 1)
ax[1].set_title('Raw SIFs')
ax[1].grid(True)
ax[1].set_ylabel('K_I')
ax[3] = fig.add_subplot(3, 2, 3)
ax[3].grid(True)
ax[3].set_ylabel('K_II')
ax[5] = fig.add_subplot(3, 2, 5)
ax[5].grid(True)
ax[5].set_xlabel('Vertex')
ax[5].set_ylabel('K_III')
ax[2] = fig.add_subplot(3, 2, 2)
ax[2].set_title('MLS SIFs')
ax[2].grid(True)
ax[2].set_ylabel('K_I')
ax[4] = fig.add_subplot(3, 2, 4)
ax[4].grid(True)
ax[4].set_ylabel('K_II')
ax[6] = fig.add_subplot(3, 2, 6)
ax[6].grid(True)
ax[6].set_xlabel('Vertex')
ax[6].set_ylabel('K_III')
for i, raw_step in enumerate(raw):
Raw_Vertex = np.arange(10)
Raw_KI = Raw_Vertex*(i+1)
Raw_KII = Raw_Vertex*(i+1)
Raw_KIII = Raw_Vertex*(i+1)
ax[1].plot(Raw_Vertex, Raw_KI, 'o-', color = blues(1 - float(i)/(len(raw)-1)))
ax[3].plot(Raw_Vertex, Raw_KII, 'o-', color = greens(1 - float(i)/(len(raw)-1)))
ax[5].plot(Raw_Vertex, Raw_KIII, 'o-', color = reds(1 - float(i)/(len(raw)-1)))
for i, mls_step in enumerate(mls):
MLS_Vertex = np.arange(10)
MLS_KI = MLS_Vertex**2*(i+1)
MLS_KII = MLS_Vertex**2*(i+1)
MLS_KIII = Raw_Vertex**2*(i+1)
ax[2].plot(MLS_Vertex, MLS_KI, 'o-', color = blues(1 - float(i)/(len(mls)-1)))
ax[4].plot(MLS_Vertex, MLS_KII, 'o-', color = greens(1 - float(i)/(len(mls)-1)))
ax[6].plot(MLS_Vertex, MLS_KIII, 'o-', color = reds(1 - float(i)/(len(mls)-1)))
plt.show()
If you want a bit more flexibility with your colour choices, then i'd suggest using colorsys;
it has some very useful functions for converting between different colour maps;
http://en.wikipedia.org/wiki/HSL_and_HSV, which can give you MUCH more flexibility.
http://docs.python.org/library/colorsys.html
you can use it like this:
ax[1].plot(Raw_Vertex, Raw_KI, 'o-', color =colorsys.hsv_to_rgb(0,1-i/float(curves),1))
It's easy to vary the lightness, darkness, and colour to anywhere you want, in a much more intuitive manner.