Wedges with label parameter, but none label in result - python

I am beginner with python (3.4) and matplotlib. I want to create a wedge with the following code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Wedge(center=(0,0), r=0.9, theta1=90, theta2=120, facecolor="red", label="Test"))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
fig1.savefig('wedge1.png', dpi=90, bbox_inches='tight')
plt.show()
All Looks fine, but the Label isn't in the plot? Any idea?

You are missing a plt.legend(). You just need to add it anywhere before the plt.show (also before fig1.savefig if you want it saved in the image) and after all your plots:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Wedge(center=(0,0), r=0.9, theta1=90, theta2=120, facecolor="red", label="Test"))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.legend() # <--- here
fig1.savefig('wedge1.png', dpi=90, bbox_inches='tight')
plt.show()
Have a look here for further details on how to use legends.

Related

Z-label does not show up in 3d matplotlib scatter plot

The z-label does not show up in my figure. What is wrong?
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
Output
Neither ax.set_zlabel("z") nor ax.set(zlabel="z") works. The x- and y-labels work fine.
That's a padding issue.
labelpadfloat The distance between the axis label and the tick labels.
Defaults to rcParams["axes.labelpad"] (default: 4.0) = 4.
You can use matplotlib.axis.ZAxis.labelpad to adjust this value for the z-axis :
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("StackOverflow", rotation=90)
ax.zaxis.labelpad=-0.7 # <- change the value here
plt.show();
Output :

Seaborn saving plots with gray background when it should be white

When I save a figure to .png, it saves with an unexpected gray background instead of white.
import matplotlib.pyplot as plt
import seaborn as sns
import random
sns.set_theme()
sns.set_style("whitegrid")
sns.set_context("poster", font_scale=1.8)
xvals = list(range(15,41))
yvals = random.sample(range(0, 50), len(xvals))
sns.set_theme()
sns.set_style("whitegrid")
sns.set_context("poster", font_scale=1.8)
fig = plt.figure()
ax = sns.lineplot(x=xvals, y=yvals)
plt.suptitle('Sample Plot')
ax.set_xlabel('x unit')
ax.set_ylabel('y unit')
ax.autoscale(enable=True, axis='y', tight=True)
fig.savefig('Results/Sample Plot.png', dpi=300, bbox_inches='tight', pad_inches=0)
The resulting figure saved as png:
What Spyder shows it looking like, and what I'm expecting to save:
You can use facecolor in figure to specify the background color, like fig = plt.figure(figsize=(10, 8), dpi=300, facecolor='#FFF') when you save the plot you can use it again like that fig.savefig(....,facecolor=fig.get_facecolor())
Your code fixed
import matplotlib.pyplot as plt
import seaborn as sns
import random
sns.set_theme()
sns.set_style("whitegrid")
sns.set_context("poster", font_scale=1.8)
xvals = list(range(15,41))
yvals = random.sample(range(0, 50), len(xvals))
sns.set_theme()
sns.set_style("whitegrid")
sns.set_context("poster", font_scale=1.8)
fig = plt.figure(facecolor='#FFF')
ax = sns.lineplot(x=xvals, y=yvals)
plt.suptitle('Sample Plot')
ax.set_xlabel('x unit')
ax.set_ylabel('y unit')
ax.autoscale(enable=True, axis='y', tight=True)
fig.savefig('Sample Plot.png', dpi=300, bbox_inches='tight', pad_inches=0,facecolor=fig.get_facecolor())

matplotlib pcolormesh grid not visible

Does anyone know why my grid is not plotted on top of the colormap here.
import matplotlib.pylab as plt
import numpy as np
Style = 'ggplot'
plt.style.use([Style])
data = np.random.random((40,40))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(data, cmap=plt.cm.viridis, zorder=1)
ax.grid(True, zorder=10)
You can use plt.rcParams["axes.axisbelow"] = False to force the grid to be on top. Note that this problem only occurs because of the use of the "ggplot" style.
Example with ggplot style:
import matplotlib.pylab as plt
import numpy as np
plt.style.use('ggplot')
plt.rcParams["axes.axisbelow"] = False
data = np.random.random((40,40))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(data, cmap=plt.cm.viridis, zorder=1)
ax.grid(True, color="crimson", lw=2)
plt.show()
Example using default style:
import matplotlib.pylab as plt
import numpy as np
data = np.random.random((40,40))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(data, cmap=plt.cm.viridis, zorder=1)
ax.grid(True, color="crimson", lw=2)
plt.show()

Creating sparklines using matplotlib in python

I am working on matplotlib and created some graphs like bar chart, bubble chart and others.
Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ?
for example with the following code
import matplotlib.pyplot as plt
import numpy as np
x=[1,2,3,4,5]
y=[5,7,2,6,2]
plt.plot(x, y)
plt.show()
the line graph generated is the following:
But I couldn't get what is the difference between a line chart and a spark lien chart for the same data. Please help me understand
A sparkline is the same as a line plot but without axes or coordinates. They can be used to show the "shape" of the data in a compact way.
You can cram several line plots in the same figure just by using subplots and changing properties of the resulting Axes for each subplot:
data = np.cumsum(np.random.rand(1000)-0.5)
data = data - np.mean(data)
fig = plt.figure()
ax1 = fig.add_subplot(411) # nrows, ncols, plot_number, top sparkline
ax1.plot(data, 'b-')
ax1.axhline(c='grey', alpha=0.5)
ax2 = fig.add_subplot(412, sharex=ax1)
ax2.plot(data, 'g-')
ax2.axhline(c='grey', alpha=0.5)
ax3 = fig.add_subplot(413, sharex=ax1)
ax3.plot(data, 'y-')
ax3.axhline(c='grey', alpha=0.5)
ax4 = fig.add_subplot(414, sharex=ax1) # bottom sparkline
ax4.plot(data, 'r-')
ax4.axhline(c='grey', alpha=0.5)
for axes in [ax1, ax2, ax3, ax4]: # remove all borders
plt.setp(axes.get_xticklabels(), visible=False)
plt.setp(axes.get_yticklabels(), visible=False)
plt.setp(axes.get_xticklines(), visible=False)
plt.setp(axes.get_yticklines(), visible=False)
plt.setp(axes.spines.values(), visible=False)
# bottom sparkline
plt.setp(ax4.get_xticklabels(), visible=True)
plt.setp(ax4.get_xticklines(), visible=True)
ax4.xaxis.tick_bottom() # but onlyt the lower x ticks not x ticks at the top
plt.tight_layout()
plt.show()
A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# create some random data
x = np.cumsum(np.random.rand(1000)-0.5)
# plot it
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k')
plt.plot(len(x)-1, x[-1], color='r', marker='o')
# remove all the axes
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
#show it
plt.show()

How can I change the font size using seaborn FacetGrid?

I have plotted my data with factorplot in seaborn and get facetgrid object, but still cannot understand how the following attributes could be set in such a plot:
Legend size: when I plot lots of variables, I get very small legends, with small fonts.
Font sizes of y and x labels (a similar problem as above)
You can scale up the fonts in your call to sns.set().
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))
sns.set(font_scale=5) # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))
The FacetGrid plot does produce pretty small labels. While #paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.
You could use the seaborn.plotting_context to change the settings for just the current plot:
with sns.plotting_context(font_scale=1.5):
sns.factorplot(x, y ...)
I've made some modifications to #paul-H code, such that you can independently set the font size for the x/y axes and legend:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);
plt.show()
This is the output:
For the legend, you can use this
plt.setp(g._legend.get_title(), fontsize=20)
Where g is your facetgrid object returned after you call the function making it.
This worked for me
g = sns.catplot(x="X Axis", hue="Class", kind="count", legend=False, data=df, height=5, aspect=7/4)
g.ax.set_xlabel("",fontsize=30)
g.ax.set_ylabel("Count",fontsize=20)
g.ax.tick_params(labelsize=15)
What did not work was to call set_xlabel directly on g like g.set_xlabel() (then I got a "Facetgrid has no set_xlabel" method error)

Categories

Resources