matplotlib.pyplot.bar plots empty graph [duplicate] - python

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.

Related

How to customiza Seaborn/Matplotlib heatmap colorbars

I need to customize the labels and ticks of an
heatmap colorbar obtained by using matplotlib with no success so far.
My data have been already posted and can be found here: 1
My working code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.read_csv("deltaGdata.csv")
df1 = df[['VARIANT', 'DDgun','mCSM', 'SDM', 'DeepDDG', 'DynaMut2']]
df1.set_index(['VARIANT'],inplace=True)
sns.set(rc = {'figure.figsize':(7, 20)}) # (width_inches, width_height)
ax = sns.heatmap(df1, cmap='rocket')
ax.set_yticks(np.arange(len(df1)) + .5)
ax.set_yticklabels(df1.index,fontname='DejaVu Sans', fontsize=14.5, fontweight='550' )
ax.set_xticklabels(df1,fontname='DejaVu Sans', fontsize=20, fontweight='550', rotation=90)
ax.set_title("ΔΔG (Kcal/mole)", fontname='DejaVu Sans', fontsize=24, fontweight='700')
figure = ax.get_figure()
figure.savefig('fig.png', dpi=300)
figure.savefig('fig.svg', dpi=300, format="svg")
This code produces an heatmap with a colorbar having very tiny ticks and numbers compared with the others
in the final figure.
I found that there is very little documentation about
how to customize colorbars and nothing useful to fix
my problem. I hope to get help also because I think it
would be beneficial for others Matplotlib/Seaborn users.
My understanding is that it consists of a heatmap and a color bar subplot, with the last subplot specifying the size of the label attribute.
print(ax.figure.axes)
[<AxesSubplot:title={'center':'ΔΔG (Kcal/mole)'}, ylabel='VARIANT'>, <AxesSubplot:label='<colorbar>'>]
# Add the following code
ax.figure.axes[-1].tick_params(labelsize=20)

Scaling and Labelling KDE plots [duplicate]

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())

Automatically determine plot size matplotlib [duplicate]

This question already has an answer here:
Inconsistent figsize resizing in matplotlib
(1 answer)
Closed 3 years ago.
I am trying to generate a bar chart with lots of bars. If I keep the figsize at defaults, the data is squeezed together and the plot is unusable.
I have the following code snippet to reproduce my problem:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1)
ax = fig.add_subplot(111)
N=100
# Example data
labels = [chr(x) for x in range(N)]
y_pos = np.arange(len(labels))
performance = 3 + 10 * np.random.rand(len(labels))
error = np.random.rand(len(labels))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(labels)
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.savefig('a.png', bbox_inches='tight')
plt.show()
If I manually set the height of the figure (for example figsize=(8,N*0.2)), the plotted data looks nice, but there is an annoying vertical whitespace before the firs bar and after the last one.
Is there any way to automatically size the plot properly?
One thing I've used is
plt.tight_layout()
it generates less whitespace for subplots, but may work with just 1 plot.
Here's more info:
https://matplotlib.org/users/tight_layout_guide.html
Another thing that may work is aspect auto when showing the plot.
plt.imshow(X, aspect='auto')
Yet another solution is 'scaled' axis
plt.axis('scaled') #this line fits your images to screen
Also if you mean the overall plot size,I generally just pick a generic size that fits, say 15 x 10 on a laptop screen, or 30x20 on a monitor. Guess and test.

Correctly setting the axes limits in matplotlib 3dplots? [duplicate]

This question already has answers here:
Removing axes margins in 3D plot
(2 answers)
Closed 4 years ago.
I'm having an issue with setting limits for my 3d plots in matplotlib; I'm finding that no matter how I set my limits for the x,y, and z axes, the plotting routine for 3dplots adds an extra buffer.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.axes.set_xlim3d(left=0, right=10)
ax.axes.set_ylim3d(bottom=0, top=10)
ax.axes.set_zlim3d(bottom=0, top=10)
plt.show()
This produces the following plot:
As you can see, the limits are supposed to be at x, y, z = {0, 10} however the 3D plotting always adds a little bit of a buffer to each edge. Does anyone know a way to turn this effect off?
I've also used plt.xlims(); and ax.axes.set_xlims() but they produce the same effect.
I think this is deliberate (see e.g. this), if you try plotting ax.axes.set_xlim3d(left=0.000001, right=9.9999999) then you get no 0 or 10 displayed on your figure.
Even making the numbers as arbitrarily close as possible doesn't work, e.g.
eps = 1e-16
ax.axes.set_xlim3d(left=0.-eps, right=10+eps)
ax.axes.set_ylim3d(bottom=0.-eps, top=10+eps)
ax.axes.set_zlim3d(bottom=0.-eps, top=10+eps)
The best solution I've found is to set the ticks manually and then slightly scale so the overlap is hidden.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.set_xticks([0,2,4,6,8,10])
ax.set_yticks([0,2,4,6,8,10])
ax.set_zticks([0,2,4,6,8,10])
ax.axes.set_xlim3d(left=0.2, right=9.8)
ax.axes.set_ylim3d(bottom=0.2, top=9.8)
ax.axes.set_zlim3d(bottom=0.2, top=9.8)
plt.show()
This gives,
This is pretty hacky but could be made more general (and I always end up setting ticks manually for publication quality figures). Alternatively, it may be better to turn off the lowest grid line or hide the grid...

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