Scaling and Labelling KDE plots [duplicate] - python

This question already has answers here:
Matplotlib Legends not working
(4 answers)
How to set the y-axis limit
(8 answers)
Closed 1 year ago.
I plotted PDF using kdeplot. I am having a tough time to scale and label the plots.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
error = np.array([1,2,2,3,4,4,5])
error2 = np.array([3,3,4,4,4,6])
sns.kdeplot(error, color='blue',label='error')
sns.kdeplot(error2, color='red',label='error2')
plt.show()
I want the blue curve to be labelled as 'error' and red curve to be labelled as 'error2'.
Also, I want to scale the y-axis. It should be in the range of 0 to 1 with 0.1 interval. How can I achieve this?
Thanks in advance

To add a legend, just add
plt.legend()
above plt.show(). To set the limit of the axis, use
ax = plt.gca() # get current axis
ax.set_ylim([0, 1])
To set the ticks accordingly, you can use
ax.set_yticks(np.arange(0, 1.1, 0.1))
(All above plt.show())

Related

matplotlib.pyplot.bar plots empty graph [duplicate]

This question already has an answer here:
'missing' bars in matplotlib bar chart
(1 answer)
Closed 5 months ago.
I'm sure I've missed something basic but I can't find anything about this by googling so here goes.
I'm trying to plot a bar chart using matplotlib.pyplot but I keep getting an empty bar chart (with the correct axis but no actual bars).
My minimal code to reproduce this is as follows:
import matplotlib.pyplot as plt
plt.bar(
x=[1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797],
height=[0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926]
)
plt.show()
I'm actually trying to plot some data calculated in pandas using pd.Crosstabs() e.g.
fig, ax = plt.subplots(1,1)
ax.bar(
x=list(df.index),
height=list(df["column1"])
)
But the problem seems to actually be with matplotlib, not with my data.
The problem is that the default bar-width is too small relative to the scale of the x-values. You can set the width as an optional parameter. For example,
import matplotlib.pyplot as plt
plt.bar(
x=[1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797],
height=[0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926],
width = 1e3
)
plt.show()
results in a reasonable graph.

How to close gap between python contour plot and colorbar [duplicate]

This question already has answers here:
Positioning the colorbar
(2 answers)
Closed 7 months ago.
I have made a contour plot and set plt.axis = 'square'. This has caused a significant gap between the plot and the color bar. I have been struggling to find a way to close this gap. How can you choose the distance between a contour plot and its color bar? How can you close this gap up to the point that they are touching?
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
plt.contourf(data)
plt.colorbar()
plt.xlabel('y label')
plt.ylabel('x label')
plt.axis('square')
You can simply use the pad attribute of plt.colorbar, and set it to -0.2 to align it with the plot itself. In case you want the colorbar bigger/smaller, you can also use the shrink attribute. More info here.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
plt.contourf(data)
plt.colorbar(pad = -0.2)
plt.xlabel('y label')
plt.ylabel('x label')
plt.axis('square')
Output:

Matplotlib squeezing x labels [duplicate]

This question already has answers here:
Rotate tick labels in subplot (Pyplot, Matplotlib, gridspec)
(3 answers)
Closed 2 years ago.
I'm trying to plot a lot a data points and the X axis is timestamps. My problem is that for some length Matplotlib automatically squeezes them together and you cannot read the x axis, as shown in the pic:
How can I prevent this from happening? I'm trying to save that plot automatically with savefig(). It is saved to a PNG.
you can specify the X-Ticks with following:
import matplotlib.pyplot as plt
plt.plot(x_values, y_value)
plt.xticks([0,5,10])
The Plot will have less ticks.
WIthout the x-ticks:
With x-ticks:
I found the answer here on the matplotlib site:
https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html
fig, ax = plt.subplots()
ax.plot(date, r.close)
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.set_title('fig.autofmt_xdate fixes the labels')

In Matplotlib, what axis attribute specifies the spacing between ticks? [duplicate]

This question already has answers here:
Changing the tick frequency on the x or y axis
(13 answers)
Closed 4 years ago.
When generating a Matplotlib line or scatter plot, what axis attribute specifies the spacing between ticks? I do not want to explicitly specify where each tick should be as prompted by this related question
ax.ticks(np.arange(-100, 100, 5))
What is the matplotlib axis attribute that controls the tick spacing? It should behave something like the following.
ax.set_x_tick_spacing(5)
This would use the same default xlim and origin point (usually 0) as the default settings.
A more recent answer to the related question illustrates using the matplotlib.ticker.MultipleLocator object. The axis ticks are this type of matplotlib object. Here is an example of it's use.
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
will place ticks 5 units apart on the x-axis, and
ax.xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(1))
will place minor ticks 1 unit apart on the x-axis.
Here is an example from the matplotlib Plotting Cookbook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
X = np.linspace(-15, 15, 1024)
Y = np.sinc(X)
ax = plt.axes()
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
ax.xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(1))
plt.plot(X, Y, c = 'k')
plt.show()

Logarithmic y axis makes tick labels disappear [duplicate]

This question already has answers here:
How to show minor tick labels on log-scale with Matplotlib
(2 answers)
Closed 7 years ago.
Upon adding the line plt.yscale('log') to my simple plotting script
import numpy as np
residuals = np.loadtxt('res_jacobi.txt', skiprows=1)
import matplotlib.pyplot as plt
fig = plt.figure()
steps = np.arange(0, len(residuals), 1)
plt.plot(steps, residuals, label='$S$')
plt.xlabel("Step",fontsize=20)
plt.ylabel("$S$",fontsize=20)
plt.ylim(0.95 * min(residuals), 1.05 * max(residuals))
plt.yscale('log')
plt.savefig('jacobi-res.pdf', bbox_inches='tight', transparent=True)
the y labels disappear.
I'm sure there is simple fix for this but searching did not turn one up. Any help would be much appreciated.
The normal behavior for matplotlib is to only label major tick marks in log-scaling --- which are even orders of magnitude, e.g. {0.1, 1.0}. Your values are all between those. You can:
rescale your axes to larger bounds,
plt.gca().set_ylim(0.1, 1.0)
label the tick-marks manually,
plt.gca().yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
semilogy works for me.
Change:
plt.plot(steps, residuals, label='$S$')
Into:
plt.semilogy(steps, residuals, label='$S$')
Remove plt.yscale('log')

Categories

Resources