Related
I have tried around 15 different methods for setting the y-label for this simple confusion matrix visualization code. Currently, I have resorted to just directly labeling the rows as 'Predicted Positive' and 'Predicted Negative' but I would prefer to have 'Predicted' outside the table like I do with 'Actual'. Very confused what's going wrong. I'm assuming it has something to do with the fact that I'm plotting a table. Removing the row labels does not fix the issue. Thanks in advance!
def plot_conf_mat(data, model_name):
'''
Plot a confusion matrix based on the array data.
Expected: 2x2 matrix of form
[[TP, FP],
[FN, TN]].
Outputs a simple colored confusion matrix table
'''
#set fontsizes
SMALL_SIZE = 20
MEDIUM_SIZE = 25
BIGGER_SIZE = 30
plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=SMALL_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# Prepare table
columns = ('Positive', 'Negative')
rows = ('Predicted\nPositive', 'Predicted\nNegative')
cell_text = data
# Add a table at the bottom of the axes
colors = [["tab:green","tab:red"],[ "tab:red","tab:grey"]]
fig, ax = plt.subplots(figsize = (6,5))
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText=cell_text,cellColours=colors,
colLabels=columns, rowLabels = rows, loc='center')
the_table.scale(2,5)
the_table.set_fontsize(20) #apparently it doesnt adhere to plt.rc??
ax.set_title(f'{model_name} Confusion Matrix: \n\nActual')
ax.set_ylabel('Predicted') #doesn't work!!
fig.savefig(f"{model_name}_conf_mat.pdf", bbox_inches = 'tight')
plt.show()
Out (model name redacted):
Firstly, did you know that there is a sklearn.metrics visualization option called ConfusionMatrixDisplay which might do what you are looking for. Do see if that helps.
For the table itself, matplotlib table is used to add a table to an axis. It usually contains a plot along with the table. As you only need a table, you are hiding the plot. If you comment out the line ax.axis('off'), you will see the borders of the plot. The ax.set_ylabel() will not work for this reason, as it is the label for the plot, which is hidden.
A simple workaround is to add text at the right place. Adding this instead of the set_ylabel() did the trick. You may need to fine tune the x and y coordinates.
plt.text(-0.155, -0.0275,'Predicted', fontsize= SMALL_SIZE, rotation=90)
I'm creating a bar chart, and I can't figure out how to add value labels on the bars (in the center of the bar, or just above it).
I believe the solution is either with 'text' or 'annotate', but I:
a) don't know which one to use (and generally speaking, haven't figured out when to use which).
b) can't see to get either to present the value labels.
Here is my code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default')
%matplotlib inline
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
fig = freq_series.plot(kind='bar')
fig.set_title('Amount Frequency')
fig.set_xlabel('Amount ($)')
fig.set_ylabel('Frequency')
fig.set_xticklabels(x_labels)
How can I add value labels on the bars (in the center of the bar, or just above it)?
Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)
x_labels = [
108300.0,
110540.0,
112780.0,
115020.0,
117260.0,
119500.0,
121740.0,
123980.0,
126220.0,
128460.0,
130700.0,
]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind="bar")
ax.set_title("Amount Frequency")
ax.set_xlabel("Amount ($)")
ax.set_ylabel("Frequency")
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = [f"label{i}" for i in range(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2, height + 5, label, ha="center", va="bottom"
)
plt.show()
This produces a labeled plot that looks like:
Based on a feature mentioned in this answer to another question I have found a very generally applicable solution for placing labels on a bar chart.
Other solutions unfortunately do not work in many cases, because the spacing between label and bar is either given in absolute units of the bars or is scaled by the height of the bar. The former only works for a narrow range of values and the latter gives inconsistent spacing within one plot. Neither works well with logarithmic axes.
The solution I propose works independent of scale (i.e. for small and large numbers) and even correctly places labels for negative values and with logarithmic scales because it uses the visual unit points for offsets.
I have added a negative number to showcase the correct placement of labels in such a case.
The value of the height of each bar is used as a label for it. Other labels can easily be used with Simon's for rect, label in zip(rects, labels) snippet.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
def add_value_labels(ax, spacing=5):
"""Add labels to the end of each bar in a bar chart.
Arguments:
ax (matplotlib.axes.Axes): The matplotlib object containing the axes
of the plot to annotate.
spacing (int): The distance between the labels and the bars.
"""
# For each bar: Place a label
for rect in ax.patches:
# Get X and Y placement of label from rect.
y_value = rect.get_height()
x_value = rect.get_x() + rect.get_width() / 2
# Number of points between bar and label. Change to your liking.
space = spacing
# Vertical alignment for positive values
va = 'bottom'
# If value of bar is negative: Place label below bar
if y_value < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
# Use Y value as label and format number with one decimal place
label = "{:.1f}".format(y_value)
# Create annotation
ax.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(0, space), # Vertically shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
ha='center', # Horizontally center label
va=va) # Vertically align label differently for
# positive and negative values.
# Call the function above. All the magic happens there.
add_value_labels(ax)
plt.savefig("image.png")
Edit: I have extracted the relevant functionality in a function, as suggested by barnhillec.
This produces the following output:
And with logarithmic scale (and some adjustment to the input data to showcase logarithmic scaling), this is the result:
As of matplotlib v3.4.0
Use matplotlib.pyplot.bar_label
The default label position, set with the parameter label_type, is 'edge'. To center the labels in the middle of the bar, use 'center'
Additional kwargs are passed to Axes.annotate, which accepts Text kwargs.
Properties like color, rotation, fontsize, etc., can be used.
See the matplotlib: Bar Label Demo page for additional formatting options.
Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
ax.containers is a list of BarContainer artists
With a single level bar plot, it's a list of len 1, hence [0] is used.
For grouped and stacked bar plots there will be more objects in the list
Stacked
Grouped
How to annotate each segment of a stacked bar chart
How to plot and annotate grouped bars in seaborn
Stacked Bar Chart with Centered Labels
How to plot and annotate a grouped bar chart
Simple label formatting can be done with the fmt parameter, as shown in the Demo examples and at How to annotate a seaborn barplot with the aggregated value.
More sophisticated label formatting should use the label parameter, as shown in the Demo examples and the following
Examples with label=
Examples with label=
stack bar plot in matplotlib and add label to each section
How to annotate a stacked bar plot and add legend labels
How to add multiple annotations to a barplot
How to customize bar annotations to not show selected values
How to plot a horizontal stacked bar with annotations
How to annotate bar plots when adding error bars
How to align annotations at the end of a horizontal bar plot
import pandas as pd
# dataframe using frequencies and x_labels from the OP
df = pd.DataFrame({'Frequency': frequencies}, index=x_labels)
# display(df)
Frequency
108300.0 6
110540.0 16
112780.0 75
115020.0 160
117260.0 244
# plot
ax = df.plot(kind='bar', figsize=(12, 8), title='Amount Frequency',
xlabel='Amount ($)', ylabel='Frequency', legend=False)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Specify additional kwargs for additional customization
Accepts parameters from matplotlib.axes.Axes.text
ax.bar_label(ax.containers[0], label_type='edge', color='red', rotation=90, fontsize=7, padding=3)
Seaborn axes-level plot
As can be seen, the is exactly the same as with ax.bar(...), plt.bar(...), and df.plot(kind='bar',...)
import seaborn as sns
# plot data
fig, ax = plt.subplots(figsize=(12, 8))
sns.barplot(x=x_labels, y=frequencies, ax=ax)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Seaborn figure-level plot
seaborn.catplot accepts a dataframe for data.
Since .catplot is a FacetGrid (subplots), the only difference is to iterate through each axes of the figure to use .bar_labels.
import pandas as pd
import seaborn as sns
# load the data into a dataframe
df = pd.DataFrame({'Frequency': frequencies, 'amount': x_labels})
# plot
g = sns.catplot(kind='bar', data=df, x='amount', y='Frequency', height=6, aspect=1.5)
# iterate through the axes
for ax in g.axes.flat:
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure; should be in the loop, otherwise only the last subplot would be adjusted
ax.margins(y=0.1)
matplotlib.axes.Axes.bar
It will be similar if just using matplotlib.pyplot.bar
import matplotlib.pyplot as plt
# create the xticks beginning a index 0
xticks = range(len(frequencies))
# plot
fig, ax = plt.subplots(figsize=(12, 8))
ax.bar(x=xticks, height=frequencies)
# label the xticks
ax.set_xticks(xticks, x_labels)
# annotate
ax.bar_label(ax.containers[0], label_type='edge')
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)
Other examples using bar_label
Linked SO Answers
Linked SO Answers
How to create and annotate a stacked proportional bar chart
How to wrap long tick labels in a seaborn figure-level plot
How to calculate percent by row and annotate 100 percent stacked bars
How to annotate barplot with percent by hue/legend group
Stacked bars are unexpectedly annotated with the sum of bar heights
How to add percentages on top of bars in seaborn
How to plot and annotate grouped bars
How to plot percentage with seaborn distplot / histplot / displot
How to annotate bar chart with values different to those from get_height()
How to plot grouped bars in the correct order
Pandas bar how to label desired values
Problem with plotting two lists with different sizes using matplotlib
How to display percentage above grouped bar chart
How to annotate only one category of a stacked bar plot
How to set ticklabel rotation and add bar annotations
How to Increase subplot text size and add custom bar plot annotations
How to aggregate group metrics and plot data with pandas
How to get a grouped bar plot of categorical data
How to plot a stacked bar with annotations for multiple groups
How to create grouped bar plots in a single figure from a wide dataframe
How to annotate a stackplot or area plot
How to determine if the last value in all columns is greater than n
How to plot grouped bars
How to plot element count and add annotations
How to add multiple data labels in a bar chart in matplotlib
Seaborn Catplot set values over the bars
Python matplotlib multiple bars
Matplotlib pie chart label does not match value
plt grid ALPHA parameter not working in matplotlib
How to horizontally center a bar plot annotation
Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
rects = ax.patches
# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha) # Horizontally align label differently for
# positive and negative values.
plt.savefig("image.png")
If you want to just label the data points above the bar, you could use plt.annotate()
My code:
import numpy as np
import matplotlib.pyplot as plt
n = [1,2,3,4,5,]
s = [i**2 for i in n]
line = plt.bar(n,s)
plt.xlabel('Number')
plt.ylabel("Square")
for i in range(len(s)):
plt.annotate(str(s[i]), xy=(n[i],s[i]), ha='center', va='bottom')
plt.show()
By specifying a horizontal and vertical alignment of 'center' and 'bottom' respectively one can get centered annotations.
I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.
def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True
if use_global_coordinate:
for i in data:
ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,fontsize=8)
c=c+1
else:
for rect,i in zip(rects,data):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')
If you only want to add Datapoints above the bars, you could easily do it with:
for i in range(len(frequencies)): # your number of bars
plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument
y = y_values[i]+1, #takes your y values as vertical positioning argument
s = data_labels[i], # the labels you want to add to the data
size = 9) # font size of datalabels
This question already has answers here:
Matplotlib make tick labels font size smaller
(10 answers)
Closed 4 years ago.
I want to increase the ticks fontsize on a plot (both x and y axes) without passing labels as an input argument to ax.set_yticklabels()
For example, say I have the y-data below (x-data doesn't matter for this example, so you could set x=np.arange(len(y)))
import numpy as np
import matplotlib.pylab as plt
y = np.array([ 5840.5, 3579.5, 2578. , 965.5, 748. , 485. ])
fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
plt.show()
Now what I would like to do is increase the fontsize of the y-ticks, but I want to leave the labels the same and in the same location as matplotlib has created them. So I tried
ax.set_yticklabels(fontsize=20)
>>> TypeError: set_yticklabels() missing 1 required positional argument: 'labels'
which of course doesn't work. But if I pass some labels as an argument
y = np.array([ 5840.5, 3579.5, 2578. , 965.5, 748. , 485. ])
fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
ax.set_yticklabels(np.arange(0,y.max(),1000), fontsize=20)
plt.show()
the fontsize does increase, but the labels and scale aren't the same as the original plot. I need to be able to change the fontsize for any array y, not just this example given above, so passing a specific label isn't possible.
Ideally what I want looks like this: the same labels and scale as in the first plot, but the y-ticks fontsize is larger. I want to produce this plot without passing labels each time I plot, because my x and y variables are dynamic. Is there a way to do this?
You can set the ytick rc param which will change the ytick fontsize for each subsequent plot using:
import matplotlib
matplotlib.rc('ytick', labelsize=20)
Alternatively if you want to do this for only one figure, you can loop through each label and change the fontsize:
for label in ax.get_yticklabels():
label.set_fontsize(20)
You can use plt.yticks() as follows:
fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
plt.yticks(fontsize=20)
plt.show()
It looks like the datapoints in the first graph accidentally overlays the second graph. The code I'm running is being run several times and it when I first have a short period and the second time I run it I have a longer period while the datapoints in the short period is also part of the longer period.
So is there a way to clean the plot before you start building a graph?
You can see the code for building the graph here:
def create_graph(self, device):
# 800 and 355 pixels.
ticks = 5
width = 8
height = 3.55
dpi = 100
bgcolor = '#f3f6f6'
font = {
'size': 16,
'family': 'Arial'
}
plt.rc('font', **font)
# size of figure and setting background color
fig = plt.gcf()
fig.set_size_inches(width, height)
fig.set_facecolor(bgcolor)
# axis color, no ticks and bottom line in grey color.
ax = plt.axes(axisbg=bgcolor, frameon=True)
ax.xaxis.set_ticks_position('none')
ax.spines['bottom'].set_color('#aabcc2')
ax.yaxis.set_ticks_position('none')
# removing all but bottom spines
for key, sp in ax.spines.items():
if key != 'bottom':
sp.set_visible(False)
# setting amounts of ticks on y axis
yloc = plt.MaxNLocator(ticks)
ax.yaxis.set_major_locator(yloc)
x_no_ticks = 8
# Deciding how many ticks we want on the graph
locator = AutoDateLocator(maxticks=x_no_ticks)
formatter = AutoDateFormatter(locator)
# Formatter always chooses the most granular since we have granular dates
# either change format or round dates depending on how granular
# we want them to be for different date ranges.
formatter.scaled[1/(24.*60.)] = '%d/%m %H:%M'
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
# turns off small ticks
plt.tick_params(axis='x',
which='both',
bottom='on',
top='off',
pad=10)
# Can't seem to set label color differently, changing tick_params color changes labels.
ax.xaxis.label.set_color('#FFFFFF')
# setting dates in x-axis automatically triggers use of AutoDateLocator
x = [datetime.fromtimestamp(point['x']) for point in device['data']]
y = [point['y'] for point in device['data']]
plt.plot(x, y, color='#53b4d4', linewidth=2)
# pick values for y-axis
y_ticks_values = np.array([point['y'] for point in device['data']])
y_ticks = np.linspace(y_ticks_values.min(), y_ticks_values.max(), ticks)
y_ticks = np.round(y_ticks, decimals=2)
plt.yticks(y_ticks, [str(val) + self.extract_unit(device) for val in y_ticks])
# plt.ylim(ymin=0.1) # Only show values of a certain threshold.
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf,
format='png',
facecolor=fig.get_facecolor(),
dpi=dpi)
You have to add plt.close() after plt.savefig(). So the figure won't be caught by the next plt.gcf() call.
I am creating a figure in Matplotlib like this:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')
I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?
Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')
For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):
axes.titlesize : large # fontsize of the axes title
axes.labelsize : medium # fontsize of the x any y labels
(As far as I can see, there is no way to set x and y label sizes separately.)
And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.
You can also do this globally via a rcParams dictionary:
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
If you're more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
I don't know of a similar way to set the suptitle size after it's created.
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.
Globally setting font sizes via rcParams should be done with
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
The defaults can be restored using
plt.rcParams.update(plt.rcParamsDefault)
You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is
axes.labelsize: 16
axes.titlesize: 16
If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
You can also create (or modify) a matplotlibrc file which shares the format
axes.labelsize = 16
axes.titlesize = 16
Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.
A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)
axes.labelsize - Fontsize of the x and y labels
axes.titlesize - Fontsize of the axes title
figure.titlesize - Size of the figure title (Figure.suptitle())
xtick.labelsize - Fontsize of the tick labels
ytick.labelsize - Fontsize of the tick labels
legend.fontsize - Fontsize for legends (plt.legend(), fig.legend())
legend.title_fontsize - Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.
all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by
font.size - the default font size for text, given in pts. 10 pt is the standard value
Additionally, the weight can be specified (though only for the default it appears) by
font.weight - The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).
If you aren't explicitly creating figure and axis objects you can set the title fontsize when you create the title with the fontdict argument.
You can set and the x and y label fontsizes separately when you create the x and y labels with the fontsize argument.
For example:
plt.title('Car Prices are Increasing', fontdict={'fontsize':20})
plt.xlabel('Year', fontsize=18)
plt.ylabel('Price', fontsize=16)
Works with seaborn and pandas plotting (when Matplotlib is the backend), too!
Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.
E.g., to make the x-axis tick label size small:
ax.xaxis.set_tick_params(labelsize='small')
or, to make the y-axis tick label large:
ax.yaxis.set_tick_params(labelsize='large')
You can also enter the labelsize as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.
An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.
Place right_ax before set_ylabel()
ax.right_ax.set_ylabel('AB scale')
libraries
import numpy as np
import matplotlib.pyplot as plt
create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))
Create bars and choose color
plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6))
Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
Create names on the x axis
plt.xticks(x_pos, bars)
Show plot
plt.show()
7 (best solution)
from numpy import*
import matplotlib.pyplot as plt
X = linspace(-pi, pi, 1000)
class Crtaj:
def nacrtaj(self,x,y):
self.x=x
self.y=y
return plt.plot (x,y,"om")
def oznaci(self):
return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)
6 (slightly worse solution)
from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
def __init__(self,m):
self.m=m
def srednja(self):
redovi = len(M)
stupci = len (M[0])
lista=[]
a=0
suma=0
while a<stupci:
for i in range (0,redovi):
suma=suma+ M[i,a]
lista.append(suma)
a=a+1
suma=0
b=array(lista)
b=b/redovi
return b
OBJ = AriSred(M)
sr = OBJ.srednja()