I'm plotting a pie chart using the following code:
fig1, ax1 = plt.subplots(figsize=(8,12))
ax1.pie(data,
labels=label,
radius=1,
startangle=90,
colors=cols,
counterclock=False,
shadow=False,
wedgeprops={'edgecolor': 'white', 'linewidth': 1},
textprops={'fontsize': 8},
pctdistance=0.85,
autopct='%1.1f%%')
plt.title('Title', fontsize=16)
plt.tight_layout()
When I change the font size in textprops both the font size of the labels and the percentages change.
What I would like to do is use different font sizes for the labels and the percentages.
I applied your code to the example in the official reference and added the code to change the font.
import matplotlib.pyplot as plt
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
l = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
cols = ['C0','C1','C2','C3']
fig1, ax1 = plt.subplots(figsize=(8,12))
wdges, labels, autopct = ax1.pie(sizes,
labels=l,
radius=1,
startangle=90,
colors=cols,
counterclock=False,
shadow=False,
wedgeprops={'edgecolor': 'white', 'linewidth': 1},
textprops={'fontsize': 8},
pctdistance=0.85,
autopct='%1.1f%%')
plt.setp(labels, fontsize=15) #update
plt.title('Title', fontsize=16)
plt.tight_layout()
Related
I Have this map, made with cartopy like this:
`
fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
fig.set_size_inches(15, 10, forward=True)
ax.set_extent([-75.5,-30,-31,6.5])
grid=ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=0.05, color='gray', alpha=0.5)
grid.top_labels = False
grid.right_labels = False
grid.xlabel_style = {'color': 'grey', 'weight': 'bold', 'size': 'small'}
grid.ylabel_style = {'color': 'grey', 'weight': 'bold', 'size': 'small'}
ax.axis('off')
precip_colormap = colors.ListedColormap(nws_precip_colors)
norm = colors.BoundaryNorm(levels, val)
data_crs = ccrs.PlateCarree()
cs = ax.contourf(lonsi, latsi, values, transform=data_crs, levels=levels, cmap=precip_colormap, add_colorbar=False, extend='both', alpha=0.8, norm=norm, edgecolor=None)
plt.title(titulo_mapa, fontsize=20, pad=30, fontweight='bold', color='grey', fontproperties=prop)
cbar=plt.colorbar(cs)
cbar.set_ticks(levels)
cbytick_obj = plt.getp(cbar.ax.axes, 'yticklabels')
plt.setp(cbytick_obj, color='grey')
and it's fine, but I want to remove this border around the colors, like this where i circled.
I didn't find any solution anywhere :(
I have this dataframe
data = {'reference':[1, 2, 3, 4, 5, 6, 7, 8, 'Total'],
'label_1':[58.3,75.0,88.0,81.1,60.0,72.0,50.0,85.7,73.8],
'label_2':[41.7, 25.0, 9.3,17.0,40.0,27.3,40.9,14.3,24.5],
'label_3':[0.0,0.0,4.7,1.9,0.0,0.8,9.1,0.0,1.7]}
data = pd.DataFrame(data).set_index('reference')
data
I have made an horizontal barplot who look like this
fig, ax = plt.subplots()
data.plot(kind='barh', stacked=True, width=0.70, ax=ax, figsize= (15, 15))
ax.legend(["label_1",
"label_2",
"label_3"], loc='upper left', bbox_to_anchor=(1, 1));
ax.yaxis.grid(True)
ax.set_axisbelow(True)
plt.xticks(rotation=0)
fmt = '%.0f%%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
for c in ax.containers:
ax.bar_label(c, label_type='center', fmt='%.0f%%')
ax.set_yticklabels( ('name_1', 'name_2','name_3', 'name_4', 'name_5', 'name_6', 'name_7', 'name_8', 'TOTAL') )
plt.show()
I want to space up the 'Total' bar, I don't have any idea how to adjust the height for only one specific bar on my plot. Any help is appreciated, thx everyone!
I'm trying to create a plot with 4 hist2d subplots and one color bar.
The thing is that each subplot can have different ranges of z values, so the color bar is not uniform.
I want to set the color bar to a pre-defined range.
here is the code I'm using:
def multiple_med_plot_test(file):
extent = [-8, 37, 28, 46]
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(26, 11), constrained_layout=True,
subplot_kw={'projection': ccrs.PlateCarree()})
ax0 = axes[0][0]
ax1 = axes[0][1]
ax2 = axes[1][0]
ax3 = axes[1][1]
axes_dict = {'Dec': ax0, 'Aug': ax1, 'Sep': ax2, 'Sum': ax3}
for month in axes_dict.keys():
ax = axes_dict[month]
ax.add_feature(cfeature.LAND, edgecolor='k', zorder=50)
ax.set_extent(extent)
gl = ax.gridlines(draw_labels=True, zorder=100, color='grey', linestyle='--')
gl.top_labels = False
gl.right_labels = False
gl.xlabel_style = {'size': 16}
gl.ylabel_style = {'size': 16}
if ax in [ax1, ax3]:
gl.left_labels = False
ax.set_title(month, fontsize=18, color='darkred')
if month != 'Sum':
hist0 = ax.hist2d(file.Long, file.Lat, range=[(-8, 37), (28, 46)], bins=(500, 200))
elif month == 'Sum':
hist1 = ax.hist2d(file.Long, file.Lat, range=[(-8, 37), (28, 46)], bins=(500, 200))
fig.suptitle('Lightning Density per Month', fontsize=22)
cbar = fig.colorbar(hist1[3], ax=axes, shrink=0.95)
cbar.set_label('# of lightnings', fontsize=20, rotation=-90, labelpad=30)
cbar.ax.tick_params(labelsize=16)
# plt.savefig('D:/Lightning Data/Yearly_Summary', dpi=100)
plt.show()
In previous versions of the code I used plt.clim and that was awesome, but the way my code is right now doesn't let me do it.
I would like to get some help on this!
If you want a linear scale, set vmin and vmax parameters. For log-like scale or similar, use norm. See hist2d documentation.
I want to display two pie-charts, well donut charts, side by side. But using the code below all I'm getting is overlapping graphs. I've tried using various values for subplot adjust but the legends always end up overlapping. Chopped out all the non relevant code in the function
#Function to draw graphs for sports data
#Create figure with two subplots
fig,ax=plt.subplots(1,2,subplot_kw=dict(aspect="equal"))
j=0
#Loop through all columns we want to graph
for type in types:
#Create a pie chart
wedges, texts, autotexts = ax[j].pie(to_plot,
explode=explode,
labels=labels,
colors=colors,
autopct=lambda pct: func(pct, data),
pctdistance=0.8,
counterclock=False,
startangle=90,
wedgeprops={'width': 0.75},
radius=1.75
)
#Set label colors
for text in texts:
text.set_color('grey')
#Create legend
ax[j].legend(wedges, leg_labels,
title=title,
title_fontsize="x-large",
loc="center left",
bbox_to_anchor=(1.5, 0, 0.5, 1),
prop={'size': 12})
j += 1
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=None)
plt.show()
return
The bbox setting that determines the position of the legend is set to the right of each pie chart, so they overlap. Therefore, we can avoid overlapping the legends by setting the respective positions for the graphs.
import matplotlib.pyplot as plt
# Some data
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
titles = ['20 members\nfollow Basketball','23 members\nfollow Basketball']
legend_pos = ['center left','center right']
bboxes = [(-1.0, 0, 0.5, 1),(1.5, 0, 0.5, 1)]
# Make figure and axes
fig, axs = plt.subplots(1, 2, subplot_kw=dict(aspect="equal"))
for i in range(2):
wedges, texts,_ = axs[i].pie(fracs,
labels=labels,
autopct='%.0f%%',
shadow=True,
explode=(0, 0.1, 0, 0),
wedgeprops=dict(width=0.6))
axs[i].legend(wedges,
labels,
title=titles[i],
title_fontsize="x-large",
loc=legend_pos[i],
bbox_to_anchor=bboxes[i],
prop={'size': 12})
plt.show()
I would like to identify the next combined histogram with a legend
import matplotlib.pyplot as plt
nbins=10
plt.title('Gaussian random numbers B-M')
plt.axis([-3, 3, 1, 25])
plotcos = plt.hist(coseno, nbins, alpha=.8, edgecolor = 'black', linewidth=1)
plotsen = plt.hist(seno, nbins, alpha=.8, edgecolor = 'black', linewidth=1)
plt.show()
Tnx
I assume by "next combined histogram" you mean individual legends for each histogram. Just use the label parameter in both your plot commands and then show the legend using plt.legend() as
plotcos = plt.hist(coseno, nbins, alpha=.8, edgecolor = 'black', linewidth=1, label='coseno')
plotsen = plt.hist(seno, nbins, alpha=.8, edgecolor = 'black', linewidth=1, label='seno')
plt.legend()