Make legend stay at bottom matplotlib python - python

I have a graph with about 30 different curves and I want to show them all in the legend. But it gets too long and they don't all fit. I want to put them down the bottom, how do I do this?
fig = plt.figure()
for i in range(len(data)):
print(i)
x1 = data.loc[0][5:-4]
y1 = data.loc[i][5:-4]
y1.replace(' ',100.0,inplace=True)
x = list(reversed(x1))
y = list(reversed(y1))
report_num = data.loc[i,'Report No']
plt.plot(x, y, label = report_num)
plt.xscale('log')
plt.grid()
plt.yticks(yints)
plt.xticks(x,x,rotation=40)
plt.title('Particle Size Distribution Curve - %s'%(report_num))
plt.legend(loc=1)

Related

Matplotlib Title location

i have this several plots and want to correct the title name location. I want to make the Vertical Acceleration (y) on the middle left vertically and the Flare Time (x) on the middle bot horizontally also the Test Title on middle top. Basically I want to be able to move the label location.
Below is the code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
x = ip.RESULTS
y = Vert
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]
nullfmt = NullFormatter() # no labels
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02
rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
# start with a rectangular Figure
plt.figure(1, figsize=(8, 8))
axScatter = plt.axes(rect_scatter)
#plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
#plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)
# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)
# the scatter plot:
axScatter.scatter(x, y, c=z, s=50, edgecolor='')
# now determine nice limits by hand:
binwidth = 1
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))])
lim = (int(xymax/binwidth) + 1) * binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x)
axHisty.hist(y, orientation='horizontal')
plt.title('test title', fontsize=20)
axHisty.set_xlabel("Vertical Acceleration")
axHistx.set_xlabel("Flare Time")
and the results look like this. Any help would be appreciated
You have three Axes objects (plot rectangles to say it sloppy) in your graph: axScatter is your main chart in the bottom left. axHisty is the histogram on the right and axHistx is the histogram on the top. Your axis titles belong on the y- and x-axis of axScatter. So just do:
axScatter.set_ylabel('Vertical Acceleration')
axScatter.set_xlabel('Flare Time')
Based on your vague question I have no idea where you want the "test title", but just figure out which Axes object is best and give it an xlabel, ylabel or title.

Embed a small radarchart into matplotlib plot

Right now I can create a radarchart as follows. Note that I made it a function just so that I can simply insert the function into my larger scatterplot more cleanly.
Radar Chart
def radarChart(PlayerLastName):
playerdf = dg.loc[dg['Player Name'] == name].index.tolist()[0]
#print(playerdf)
labels=np.array(['SOG', 'SH', 'G', 'A'])
stats=dg.loc[playerdf,labels].values
#print(stats)
# Set the angle of polar axis.
# And here we need to use the np.concatenate to draw a closed plot in radar chart.
angles=np.linspace(0, 2*np.pi, len(labels), endpoint=False)
# close the plot
stats=np.concatenate((stats,[stats[0]]))
angles=np.concatenate((angles,[angles[0]]))
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, stats, 'o-', linewidth=1)
ax.fill(angles, stats, alpha=0.3)
ax.set_thetagrids(angles * 180/np.pi, labels)
#plt.title(PlayerLastName + ' vs. ' + namegame)
ax.grid(True)
return
I then want to put this figure in the bottom right of my scatter plot I have elsewhere. This other article does not provide me with any way to do this since my plot is circular. Any help would be great!
When I call radarChart('someones name') I get
I would really like to not have to save it as an image first and then put it in the plot.
I am not sure, what your desired output is. You should always provide a Minimal, Complete, and Verifiable example. Apart from this, I don't know, why a polar plot would be different from any other plot to create an inset:
import matplotlib.pyplot as plt
import numpy as np
#function for the polar plot
def radarChart(Player = "SOG", left = .3, bottom = .6, width = .2, height = .2):
#labels and positions
labels = np.array(['SOG', 'SH', 'G', 'A'])
angles = np.linspace(0, 360, len(labels), endpoint = False)
#inset position
ax = plt.axes([left, bottom, width, height], facecolor = "lightblue", polar = True)
#label polar chart
ax.set_thetagrids(angles, labels)
#polar chart title
plt.title(Player, loc = "left")
return ax
#main figure
x = np.linspace (-3, 1, 1000)
y = 2 * np.exp(3 - x) - 1
plt.plot(x, y)
plt.xlabel("x values")
plt.ylabel("y values")
plt.title("figure with polar insets")
#inset 1
ax = radarChart(Player = "A")
plt.scatter(x[::50], y[::50])
#inset 2
ax = radarChart(left = .6, bottom = .4, width = .2, height = .2)
plt.plot(x, y)
plt.show()
Sample output:

Python Matplotlib Twinx() cursor values

I want to use the cursor (x,y values get displayed at the bottom left of figure) to measure the y and x distance between two points, however this only works for the data plotted on the second axis.
Is there a way to switch back an forth between the second axis and first y-axis?
Please note: I do not want a programmatic way of getting distance between points, just to use the cursor when I am viewing data in the figure plot.
Not sure if this helps but my code is literally the example for plotting two axes from the matplotlib page:
fig, ax1 = plt.subplots()
ax1.plot(sensor1, 'b-')
ax1.set_xlabel('(time)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
ax2.plot(sensor2, 'r.')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()
You can use the excellent answer here to get both coordinates displayed at the same time. In order to get distance between two points, you can then combine this idea with ginput to map from one to the other and add the result as a title,
import matplotlib.pyplot as plt
import numpy as np
#Provide other axis
def get_othercoords(x,y,current,other):
display_coord = current.transData.transform((x,y))
inv = other.transData.inverted()
ax_coord = inv.transform(display_coord)
return ax_coord
#Plot the data
fig, ax1 = plt.subplots()
t = np.linspace(0,2*np.pi,100)
ax1.plot(t, np.sin(t),'b-')
ax1.set_xlabel('(time)')
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
ax2.plot(t,3.*np.cos(t),'r-')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
#Get user input
out = plt.ginput(2)
#2nd axis from input
x2b, x2t = out[0][0], out[1][0]
y2b, y2t = out[0][1], out[1][1]
#Draw line
ax2.plot([x2b, x2t],[y2b, y2t],'k-',lw=3)
#1st axis from transform
x1b, y1b = get_othercoords(x2b,y2b,ax2,ax1)
x1t, y1t = get_othercoords(x2t,y2t,ax2,ax1)
plt.title("Distance x1 = " + str(x1t-x1b) + " y1 = " + str(y1t-y1b) + "\n"
"Distance x2 = " + str(x2t-x2b) + " y2 = " + str(y2t-y2b))
plt.draw()
plt.show()
which gives something like,

Adding labels to legend post plotting

I have to plot 2 lines and then measure the absolute distance between them. This distance then becomes the label for the legend.
Pseudo Code looks something like this:
for line in file:
# extract data here
sample = sns.kdeplot(data)
perfect_template = sns.kdeplot(perfect_template_data)
sample_line = sample.get_lines()[iterate].get_data()
perfect_line = perfect_template.get_lines()[iterate]get_data()
absolute_diff = sum(abs(np.diff(zip(sample_line, perfect_line))))
label = absolute_diff
sample = sns.kdeplot(data, linewidth=1, label=label)
plt(legend)
pp.savefig()
This requires me to plot sns.kdeplot twice.
Is there a way to add the label to the initial sns.kdeplot without re-plotting?
You can use set_label() like this:
sample.set_label(label)
I.e. for a minimal example:
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
y2 = np.sin(2*x)
first_line, = plt.plot(x, y)
plt.plot(x, y2)
first_line.set_label('First line')
plt.legend()

Laying out several plots in matplotlib + numpy

I am pretty new to python and want to plot a dataset using a histogram and a heatmap below. However, I am a bit confused about
How to put a title above both plots and
How to insert some text into bots plots
How to reference the upper and the lower plot
For my first task I used the title instruction, which inserted a caption in between both plots instead of putting it above both plots
For my second task I used the figtext instruction. However, I could not see the text anywhere in the plot. I played a bit with the x, y and fontsize parameters without any success.
Here is my code:
def drawHeatmap(xDim, yDim, plot, threshold, verbose):
global heatmapList
stableCells = 0
print("\n[I] - Plotting Heatmaps ...")
for currentHeatmap in heatmapList:
if -1 in heatmapList[currentHeatmap]:
continue
print("[I] - Plotting heatmap for PUF instance", currentHeatmap,"(",len(heatmapList[currentHeatmap])," values)")
# Convert data to ndarray
#floatMap = list(map(float, currentHeatmap[1]))
myArray = np.array(heatmapList[currentHeatmap]).reshape(xDim,yDim)
# Setup two plots per page
fig, ax = plt.subplots(2)
# Histogram
weights = np.ones_like(heatmapList[currentHeatmap]) / len(heatmapList[currentHeatmap])
hist, bins = np.histogram(heatmapList[currentHeatmap], bins=50, weights=weights)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
ax[0].bar(center, hist, align='center', width=width)
stableCells = calcPercentageStable(threshold, verbose)
plt.figtext(100,100,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", fontsize=40)
heatmap = ax[1].pcolor(myArray, cmap=plt.cm.Blues, alpha=0.8, vmin=0, vmax=1)
cbar = fig.colorbar(heatmap, shrink=0.8, aspect=10, fraction=.1,pad=.01)
#cbar.ax.tick_params(labelsize=40)
for y in range(myArray.shape[0]):
for x in range(myArray.shape[1]):
plt.text(x + 0.5, y + 0.5, '%.2f' % myArray[y, x],
horizontalalignment='center',
verticalalignment='center',
fontsize=(xDim/yDim)*5
)
#fig = plt.figure()
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(60.5,55.5)
plt.savefig(dataDirectory+"/"+currentHeatmap+".pdf", dpi=800, papertype="a3", format="pdf")
#plt.title("Heatmap for PUF instance "+str(currentHeatmap[0][0])+" ("+str(numberOfMeasurements)+" measurements; "+str(sizeOfMeasurements)+" bytes)")
if plot:
plt.show()
print("\t[I] - Done ...")
And here is my current output:
Perhaps this example will make things easier to understand. Things to note are:
Use fig.suptitle to add a title to the top of a figure.
Use ax[i].text(x, y, str) to add text to an Axes object
Each Axes object, ax[i] in your case, holds all the information about a single plot. Use them instead of calling plt, which only really works well with one subplot per figure or to modify all subplots at once. For example, instead of calling plt.figtext, call ax[0].text to add text to the top plot.
Try following the example code below, or at least read through it to get a better idea how to use your ax list.
import numpy as np
import matplotlib.pyplot as plt
histogram_data = np.random.rand(1000)
heatmap_data = np.random.rand(10, 100)
# Set up figure and axes
fig = plt.figure()
fig.suptitle("These are my two plots")
top_ax = fig.add_subplot(211) #2 rows, 1 col, 1st plot
bot_ax = fig.add_subplot(212) #2 rows, 1 col, 2nd plot
# This is the same as doing 'fig, (top_ax, bot_ax) = plt.subplots(2)'
# Histogram
weights = np.ones_like(histogram_data) / histogram_data.shape[0]
hist, bins = np.histogram(histogram_data, bins=50, weights=weights)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
# Use top_ax to modify anything with the histogram plot
top_ax.bar(center, hist, align='center', width=width)
# ax.text(x, y, str). Make sure x,y are within your plot bounds ((0, 1), (0, .5))
top_ax.text(0.5, 0.5, "Here is text on the top plot", color='r')
# Heatmap
heatmap_params = {'cmap':plt.cm.Blues, 'alpha':0.8, 'vmin':0, 'vmax':1}
# Use bot_ax to modify anything with the heatmap plot
heatmap = bot_ax.pcolor(heatmap_data, **heatmap_params)
cbar = fig.colorbar(heatmap, shrink=0.8, aspect=10, fraction=.1,pad=.01)
# See how it looks
plt.show()

Categories

Resources