Matplotlib 2 inconsistent font - python

I updated Anaconda Python to the latest version (4.3), where they upgraded Matplotlib to version 2.
The upgrade has made some major changes to the default style (see here).
And, while I really like some of those changes, I am not in agreement with a few of them.
Hence I did some modifications, as suggested in the link above:
#%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib
# http://matplotlib.org/users/dflt_style_changes.html
params = {'legend.fontsize': 18,
'axes.labelsize': 18,
'axes.titlesize': 18,
'xtick.labelsize' :12,
'ytick.labelsize': 12,
'mathtext.fontset': 'cm',
'mathtext.rm': 'serif',
'grid.color': 'k',
'grid.linestyle': ':',
'grid.linewidth': 0.5,
}
matplotlib.rcParams.update(params)
x = sc.linspace(0,100)
y = x**2
fig = plt.figure('Fig')
ax = fig.add_subplot(1, 1, 1)
lines = ax.semilogy(x, y)
ax.set_yticks([300], minor=True)
ax.yaxis.grid(True, which='minor')
ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.tick_params(axis='y', pad=10)
ax.set_xlabel(r'$\mathrm{R_L}$')
ax.set_ylabel(r'$\sigma \int_l \; dx$')
#fig.savefig('./PNG/test.png', dpi=300, bbox_inches='tight')
Using Latex as the axes labels, as in the code above, results in a figure with inconsistent text on axes (see the following image).
How to get back to the previous behaviour (see the image below) or to a consistent font scheme?
EDIT:
Using the Latex back-end I am able to get a good result, but it is extremely slow.
Anyway, I think the internal back-end should be able to get a consistent output and switching to a different back-end is not a real solution, but more a workaround.
To use the latex back-end:
#%matplotlib inline
#%matplotlib notebook
#%config InlineBackend.figure_format = 'svg'
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib
# http://matplotlib.org/users/dflt_style_changes.html
params = {'legend.fontsize': 18,
'axes.labelsize': 18,
'axes.titlesize': 18,
'xtick.labelsize' :12,
'ytick.labelsize': 12,
'mathtext.fontset': 'cm',
'mathtext.rm': 'serif',
'grid.color': 'k',
'grid.linestyle': ':',
'grid.linewidth': 0.5,
}
matplotlib.rcParams.update(params)
matplotlib.rcParams.update({'text.usetex':True, 'text.latex.preamble':[r'\usepackage{amsmath, newtxmath}']})
x = sc.linspace(0,100)
y = x**2
fig = plt.figure('Fig')
ax = fig.add_subplot(1, 1, 1)
lines = ax.semilogy(x, y)
ax.set_yticks([300], minor=True)
ax.yaxis.grid(True, which='minor')
ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.tick_params(axis='y', pad=10)
ax.set_xlabel(r'$\mathrm{R_L}$')
ax.set_ylabel(r'$\sigma \int_l \; dx$')
#fig.savefig('./PNG/test.png', dpi=300, bbox_inches='tight')
The result with matplotlib 2 is:
The resulting plot with the older version is (still a bit different, maybe due to some latex differences):
But again, the desired result is what obtained from an older version of matplotlib and in displayed in figure 2.

If consistency is the only issue, you can use a "Roman" style using the "Times" font. It is not necessary to use Latex via usetex. Instead simply use the STIX fontset, the Times font and serif mathtext.
import scipy as sc
import matplotlib.style
import matplotlib.pyplot as plt
params = {'legend.fontsize': 18,
'axes.labelsize': 18,
'axes.titlesize': 18,
'xtick.labelsize' :12,
'ytick.labelsize': 12,
'grid.color': 'k',
'grid.linestyle': ':',
'grid.linewidth': 0.5,
'mathtext.fontset' : 'stix',
'mathtext.rm' : 'serif',
'font.family' : 'serif',
'font.serif' : "Times New Roman", # or "Times"
}
matplotlib.rcParams.update(params)
x = sc.linspace(0,100)
y = x**2
fig = plt.figure('Fig')
ax = fig.add_subplot(1, 1, 1)
lines = ax.semilogy(x, y)
ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.tick_params(axis='y', pad=10)
ax.set_yticks([300], minor=True)
ax.yaxis.grid(True, which='minor')
ax.set_xlabel(r'$\mathrm{R_L}$')
ax.set_ylabel(r'$\sigma \int_l \; dx$')
plt.tight_layout()
plt.show()

From the link you did provide:
A ‘classic’ style sheet is provided so reverting to the 1.x default values is a single line of python
mpl.style.use('classic')
Adding this line
matplotlib.style.use('classic')
to your script should solve your problem.
I tested it on my python2.7/matplotlib 2, and it worked fine (i.e. I get back the matplotlib 1.x fonts).

While trying to find a solution to my question, I tried comparing the dictionaries of the old and new rcParams and setting the elements which were different and related to mathtext font: the result is quite good.
The code is:
#%matplotlib inline
#%matplotlib notebook
#%config InlineBackend.figure_format = 'svg'
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib
# http://matplotlib.org/users/dflt_style_changes.html
params = {'legend.fontsize': 18,
'axes.labelsize': 18,
'axes.titlesize': 18,
'xtick.labelsize' :12,
'ytick.labelsize': 12,
'mathtext.fontset': 'cm',
'mathtext.rm': 'serif',
'mathtext.bf': 'serif:bold',
'mathtext.it': 'serif:italic',
'mathtext.sf': 'sans\\-serif',
'grid.color': 'k',
'grid.linestyle': ':',
'grid.linewidth': 0.5,
}
matplotlib.rcParams.update(params)
#matplotlib.rcParams.update({'text.usetex':True, 'text.latex.preamble':[r'\usepackage{amsmath, newtxmath}']})
#matplotlib.rcParams.update({'text.usetex':True, 'text.latex.preamble':[r'\usepackage{amsmath, mathptmx}']})
#matplotlib.rcParams.update({'text.usetex':True, 'text.latex.preamble':[r'\usepackage{amsmath}']})
x = sc.linspace(0,100)
y = x**2
fig = plt.figure('Fig')
ax = fig.add_subplot(1, 1, 1)
lines = ax.semilogy(x, y)
ax.set_yticks([300], minor=True)
ax.yaxis.grid(True, which='minor')
ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.tick_params(axis='y', pad=10)
ax.set_xlabel(r'$\mathrm{R_L}$')
ax.set_ylabel(r'$\sigma \int_l \; dx$')
fig.savefig('./PNG/test.png', dpi=300, bbox_inches='tight')
hence adding also:
'mathtext.rm': 'serif',
'mathtext.bf': 'serif:bold',
'mathtext.it': 'serif:italic',
'mathtext.sf': 'sans\\-serif',
which results in:
that I consider quite good and consistent in a Latex document.
The other answer in this thread from #ImportanceOfBeingErnest is also neat and nice.

Related

plt grid ALPHA parameter not working in matplotlib

I have the current function which generates a simple chart in matplotlib but as we see in the image the alpha parameter not seems to work, this happen in vs code, if I test this in a notebook works fine
what i need is the same format in vs code
data:
,hora,id
0,0,10
1,1,3
2,2,2
3,3,3
4,4,5
5,5,3
6,6,11
7,7,32
8,8,41
9,9,71
10,10,75
11,11,70
12,12,57
13,13,69
14,14,50
15,15,73
16,16,47
17,17,64
18,18,73
19,19,54
20,20,45
21,21,43
22,22,34
23,23,27
code:
import pandas as pd
from matplotlib import pyplot as plt
dfhoras=pd.read_clipboard(sep=',')
def questionsHour(dfhoras):
x = dfhoras['hora']
y = dfhoras['id']
horas=[x for x in range(24)]
plt.figure(facecolor="w")
plt.figure(figsize=(15,3))
plt.rcParams['axes.spines.top'] = False
plt.bar(x, y,linewidth=3,color="#172a3d")
plt.xticks(horas,fontweight='bold',color="#e33e31",fontsize=9)
plt.yticks(fontweight='bold',color="#e33e31",fontsize=9)
plt.grid(color="#172a3d", linestyle='--',linewidth=1,axis='y',alpha=0.15)
#aca creo las etiquetas de los puntos
for x,y in zip(x,y):
label = "{:.2f}".format(y)
plt.annotate(label,
(x,y),
textcoords="offset points",
xytext=(0,5),
ha='center',
fontsize=9,
fontweight='bold',
color="#e33e31")
plt.savefig('questions1.png',dpi=600,transparent=True,bbox_inches='tight')
questionsHour(dfhoras)
this is the result in vs code
and this is the result in a notebook
Make sure the environment packages used by VSCode are updated, as they aren't necessarily the same as those being used by Jupyter.
Tested in python 3.8.11, pandas 1.3.2, matplotlib 3.4.3
I was originally testing with matplotlib 3.4.2, which seems to have a bug and would not set weight='bold', so if VSCode is using a different package version, there could be a bug with alpha=0.15.
The OP uses plt.figure(facecolor="w") and plt.figure(figsize=(15,3)), which creates two different figures (not noticeable with inline plots, but two windows will open if using interactive plots). It should be plt.figure(facecolor="w", figsize=(15, 3)).
The following code uses the object oriented approach with axes, which makes sure all methods are applied to the correct axes being plotted.
Plot the dataframe directly with pandas.DataFrame.plot, which uses matplotlib as the default backend, and returns an axes.
Annotations are made using matplotlib.pyplot.bar_label
import pandas as pd
# test data
data = {'hora': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], 'id': [10, 3, 2, 3, 5, 3, 11, 32, 41, 71, 75, 70, 57, 69, 50, 73, 47, 64, 73, 54, 45, 43, 34, 27]}
df = pd.DataFrame(data)
# plot function
def questionsHour(df):
ax = df.plot(x='hora', y='id', figsize=(15, 3), linewidth=3, color="#172a3d", rot=0, legend=False, xlabel='', kind='bar', width=0.75)
ax.set_xticklabels(ax.get_xticklabels(), weight='bold', color="#e33e31", fontsize=9)
ax.set_yticks(ax.get_yticks()) # prevents warning for next line
ax.set_yticklabels(ax.get_yticks(), weight='bold', color="#e33e31", fontsize=9)
ax.grid(color="#172a3d", linestyle='--', linewidth=1, axis='y', alpha=0.15)
ax.spines['top'].set_visible(False)
ax.bar_label(ax.containers[0], fmt='%.2f', fontsize=9, weight='bold', color="#e33e31")
questionsHour(df)

Filling the area between two lines on different scales/subplot axes

I am trying to figure out how to fill between two lines that are on different scales & axes of subplot, however, I have not been able to figure out how to do this.
I have tried following the answer here for a similar question, but the formula supplied in the code doesn't work on my dataset and based on the responses from the author of that question the equation doesn't appear to work when the x limits are changed.
The following image is what I am after (created in Photoshop):
However, using the code below, I get:
Example Data & Code
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame({'DEPTH':[4300, 4310, 4320, 4330, 4340, 4350, 4360, 4370, 4380, 4390],
'NEUT':[45, 40, 30, 12, 6, 12, 8, 10, 20, 18],
'DENS':[2.5, 2.55, 2.32, 2.35, 2.3, 2.55, 2.58, 2.6, 2.52, 2.53]})
fig = plt.subplots(figsize=(7,20))
ax1 = plt.subplot2grid((1,1), (0,0))
ax2 = ax1.twiny()
ax1.plot('DENS', 'DEPTH', data=data, color='red')
ax1.set_xlim(1.95, 2.95)
ax1.set_xlabel('Density')
ax1.xaxis.label.set_color("red")
ax1.tick_params(axis='x', colors="red")
ax1.spines["top"].set_edgecolor("red")
ax2.plot('NEUT', 'DEPTH', data=data, color='blue')
ax2.set_xlim(45, -15)
ax2.set_xlabel('Neutron')
ax2.xaxis.label.set_color("blue")
ax2.spines["top"].set_position(("axes", 1.04))
ax2.tick_params(axis='x', colors="blue")
ax2.spines["top"].set_edgecolor("blue")
ax1.fill_betweenx(data['DEPTH'], data['DENS'], data['NEUT'], where=data['DENS']>=data['NEUT'], interpolate=True, color='green')
ax1.fill_betweenx(data['DEPTH'], data['DENS'], data['NEUT'], where=data['DENS']<=data['NEUT'], interpolate=True, color='yellow')
for ax in [ax1, ax2]:
ax.set_ylim(4400, 4300)
ax.xaxis.set_ticks_position("top")
ax.xaxis.set_label_position("top")
Would anyone be able to help me with this please?
The difference between your code and the answer you linked is that your Neutron scale goes from the maximum value on the left to the minimum value on the right, which means the logic is slightly wrong. So we just need to switch a few min and max terms around.
Try this:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame({'DEPTH':[4300, 4310, 4320, 4330, 4340, 4350, 4360, 4370, 4380, 4390],
'NEUT':[45, 40, 30, 12, 6, 12, 8, 10, 20, 18],
'DENS':[2.5, 2.55, 2.32, 2.35, 2.3, 2.55, 2.58, 2.6, 2.52, 2.53]})
fig = plt.subplots(figsize=(6,8))
ax1 = plt.subplot2grid((1,1), (0,0))
ax2 = ax1.twiny()
ax1.plot('DENS', 'DEPTH', data=data, color='red')
ax1.set_xlim(1.95, 2.95)
ax1.set_xlabel('Density')
ax1.xaxis.label.set_color("red")
ax1.tick_params(axis='x', colors="red")
ax1.spines["top"].set_edgecolor("red")
ax2.plot('NEUT', 'DEPTH', data=data, color='blue')
ax2.set_xlim(45, -15)
ax2.set_xlabel('Neutron')
ax2.xaxis.label.set_color("blue")
ax2.spines["top"].set_position(("axes", 1.08))
ax2.tick_params(axis='x', colors="blue")
ax2.spines["top"].set_edgecolor("blue")
x = np.array(ax1.get_xlim())
z = np.array(ax2.get_xlim())
x1 = data['DENS']
x2 = data['NEUT']
nz=((x2-np.max(z))/(np.min(z)-np.max(z)))*(np.max(x)-np.min(x))+np.min(x)
ax1.fill_betweenx(data['DEPTH'], x1, nz, where=x1>=nz, interpolate=True, color='green')
ax1.fill_betweenx(data['DEPTH'], x1, nz, where=x1<=nz, interpolate=True, color='yellow')
for ax in [ax1, ax2]:
ax.set_ylim(4400, 4300)
ax.xaxis.set_ticks_position("top")
ax.xaxis.set_label_position("top")
plt.show()
(I changed the figure size so it would fit on my screen)

How can I make the legend text 'bold ' in Python

I want to make the legend 'bold' I also want to change the font style of the legend like times new roman etc.
plt.gca().legend(('Experimental Values','Simulated Values'))
params = {'legend.fontsize': 15, 'legend.handlelength': 1}
plot.rcParams.update(params)
plt.figure(figsize=(6,6))
edit/update:
I have found a nice and complete example here
Try this:
import numpy as np
import matplotlib.font_manager as font_manager
fig, (ax0) = plt.subplots(1, 1, figsize=(10,5));
xx = np.arange(10)
yy = 0.3*xx
plt.plot(xx,yy,label='Line')
font = font_manager.FontProperties(family= 'Comic Sans MS', # 'Times new roman',
weight='bold',
style='normal', size=25)
plt.legend(loc="best" , prop=font)
plt.show()
The following code solved my problem.
plt.gca().legend(('Experimental Values','Simulated Values'))
params = {'legend.fontsize':10, 'legend.handlelength': 1, 'font.weight': 'bold'}
plot.rcParams.update(params)
plt.figure(figsize=(6,6))

Legend is cut off, solving the issue is affecting the font size in an unwanted way

I am creating a figure in Matplotlib with the following code and I hope it is not too messy:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import locale
locale.setlocale(locale.LC_ALL, 'German')
#the data to be plotted
CSB = [9205.0, 8845.0, 19740.0, 410.0, 11560.0, 11632.0, 14368.0,
11556.0, 9846.0, 14544.0]
DOC = [np.nan, 1853.0, 4172.0, 259.0, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan]
NH3N = [3593.5, 3318.8, 5208.0, 306.4, 2708.2, 2682.1, 2812.3, 3033.1,
3098.4, 3815.9]
x = np.linspace(1, 10, 10)
Daten = ['09.05.2017', '16.05.2017', '23.05.2017', '06.06.2017', '28.08.2017',
'31.08.2017', '04.09.2017', '07.09.2017', '14.09.2017', '18.09.2017']
#setting the font and font size globally
font = {'family' : 'Arial',
'size' : 12}
matplotlib.rc('font', **font)
fig, ax1 = plt.subplots()
#first plot
l1, = ax1.plot(x, NH3N, 'k+', label='NH$_3$-N-Konzentration', ms=8)
ax1.set_ylabel(r'NH$_3$-N-Konzentration $[\frac{mg}{L}]$')
ax1.set_xlabel('Datum Probenahme')
ax1.set_ylim([0,10000])
ax1.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
#getting the x tick lables fitted to dates
plt.xticks(x, Daten, rotation=30)
fig.autofmt_xdate()
plt.subplots_adjust(bottom=0.3)
#second plot as a parasite of the first
ax2 = ax1.twinx()
l2, = ax2.plot(x, CSB, 'k.', label='CSB-Konzentration', ms=8)
ax2.set_ylabel(r'CSB-Konzentration $[\frac{mg}{L}]$')
ax2.set_ylim([0,25000])
ax2.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
#third plot as a parasite of the first
ax3 = ax1.twinx()
l3, = ax3.plot(x, DOC, 'k^', label='DOC-Konzentration', ms=8)
ax3.set_ylabel(r'DOC-Konzentration $[\frac{mg}{L}]$')
ax3.set_ylim([0,5000])
ax3.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
#manipulating the position of the third y axis
ax3.tick_params(direction='in', pad=-50)
ax3.spines['left'].set_position(('axes', 1.3))
ax3.yaxis.set_ticks_position('left')
ax3.yaxis.set_label_coords(1.48,0.5)
fig.legend((l1,l2,l3),('NH$_3$-N-Konzentration','CSB-Konzentration',
'DOC-Konzentration'), loc=9, ncol = 3, bbox_to_anchor=(0.75, 0.15))
plt.savefig('CSB_NH3N_DOC_unbehandeltes_Abwasser.eps', format='eps',
dpi=1000, bbox_inches='tight')
plt.show()
The code is resulting in this graph, which is supposed to be part of a Latex file. I am pretty new to Python, so I might have overlooked something or there might be other issues, besides the one I am asking for: I am sorry for that.
Now to my problem: the legend is supposed to be below the figure, which I can accomplish with the bbox_to_anchor attribute. This results in a cut off legend, a problem I tried to solve with
plt.margins(0.2)
plt.subplots_adjust(bottom=0.30)
and/or
plt.tight_layout()
and/or
bbox_inches='tight'
In the end, all of this is either scaling the hole figure in an awkward way or at least scaling the font size, an issue that gets obvious, when the figure is added to the Latex file. I think the whole twinx() thing is making everything quite unstable, but for me as a newbie it seemed to be an easier solution than this. Reading a lot of questions like this to find an answer it seems there is no easy way like "just add some space to the bottom manually without scaling", but I have to try and ask anyway.
Is there a way to put the legend to the very bottom of the figure and keeping the font size and the look of the figure as it is i.e. without any scaling commands?
Use
loc="lower center", bbox_to_anchor=(0.5, 0.)
where "lower" means that the anchor point's y coordinate (0.) refers to the lower border of the legend and "center" that the x coordinate (0.5) refers to the center of the legend. Both coordinates have a range of 0 to 1. This is illustrated in How to specify legend position in matplotlib in graph coordinates
I now followed the general example and with some help I was able to get to the result I aimed at. Here is the code with a proper positioning of the legend:
import matplotlib.pyplot as plt
import numpy as np
CSB = [9205.0, 8845.0, 19740.0, 410.0, 11560.0, 11632.0, 14368.0,
11556.0, 9846.0, 14544.0]
DOC = [np.nan, 1853.0, 4172.0, 259.0, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan]
NH3N = [3593.5, 3318.8, 5208.0, 306.4, 2708.2, 2682.1, 2812.3, 3033.1,
3098.4, 3815.9]
x = np.linspace(1, 10, 10)
Daten = ['09.05.2017', '16.05.2017', '23.05.2017', '06.06.2017', '28.08.2017',
'31.08.2017', '04.09.2017', '07.09.2017', '14.09.2017', '18.09.2017']
font = {'family' : 'Arial',
'size' : 12}
plt.rc('font', **font)
fig = plt.figure()
host = fig.add_subplot(111)
par1 = host.twinx()
par2 = host.twinx()
host.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
par1.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
par2.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x,
loc: "{0:n}".format(float(x))))
offset = 85
par2.spines['right'].set_position(('outward', offset))
host.set_xlim(0, 11)
host.set_ylim(0, 10000)
host.set_xlabel("Datum Probenahme")
host.set_ylabel(r'NH$_3$-N-Konzentration $[\frac{mg}{L}]$')
par1.set_ylabel(r'CSB-Konzentration $[\frac{mg}{L}]$')
par2.set_ylabel(r'DOC-Konzentration $[\frac{mg}{L}]$')
host.set_xticks(x)
host.set_xticklabels(Daten)
p1, = host.plot(x, NH3N, '+k', label='NH$_3$-N-Konzentration')
p2, = par1.plot(x, CSB, '.k', label=r'CSB-Konzentration')
p3, = par2.plot(x, DOC, '^k', label=r'DOC-Konzentration')
par1.set_ylim(0, 25000)
par2.set_ylim(0, 5000)
host.legend((p1,p2,p3),('NH$_3$-N-Konzentration','CSB-Konzentration','DOC-Konzentration'), loc='lower center', ncol = 3, bbox_to_anchor=(0.5, -0.5))
fig.autofmt_xdate()
plt.tight_layout()
plt.show()
Next time I will take an even closer look at the gallery. Thanks a lot for your time!

Pretty plot bar chart in python with matplotlib

I wrote a python code below to draw a bar chart for my data. I adjusted parameters but failed to make it beautiful(See attached pic).
The python code is shown below:
def plotElapsedDis(axis, jvm1, jvm2, ylabel, title, name):
import matplotlib.pyplot as plt
import numpy as np
#fig, ax = plt.subplots(111)
fig = plt.figure()
ax = fig.add_subplot(111)
## the data
N = len(jvm1)
#menMeans = [18, 35, 30, 35, 27]
#womenMeans = [25, 32, 34, 20, 25]
ind = np.arange(N)+1
width = 0.25 # the width of the bars
rects1 = ax.bar(ind-width, jvm1, width)
rects2 = ax.bar(ind, jvm2, width, color='r')
ax.set_ylabel(ylabel)
ax.set_title(title)
plt.xticks(ind , axis, rotation=-90)
ax.legend( (rects1[0], rects2[0]), ('Originl', 'Optimal') )
plt.savefig(name)
plt.close()
plotElapsedDis(keys, y_jvm1, y_jvm2, 'seconds', 'CPU Elapsed', '../tmp/cpu_elapsed.jpg')
The first three lists for plotElapsedDis are:
keys= [u'mergesort_hongli', u'so_object', u'gc_mb', u'socket_transfer_1mb', u'app_factorial', u'string_concat', u'printff', u'so_lists', u'so_lists_small', u'word_anagrams', u'fasta', u'count_multithreaded', u'app_mandelbrot', u'primes', u'nbody', u'app_fib', u'socket_transfer_1mb_noblock', u'nsieve_bits', u'gc_string', u'simple_server', u'gc_array', u'cal', u'spectral_norm', u'app_pentomino', u'so_sieve', u'eval', u'so_matrix', u'mbari_bogus1', u'fractal', u'simple_connect', u'partial_sums', u'pi', u'so_array', u'count_shared_thread', u'fiber_ring', u'list', u'binary_trees', u'app_tarai', u'monte_carlo_pi', u'observ', u'write_large']
y_jvm1= [20.703852000000001, 173.12867899999998, 74.149726000000001, 15.717608999999999, 26.226012000000001, 136.44825599999999, 46.775888000000002, 63.851292000000001, 13.929881, 71.078192999999999, 66.729854000000003, 92.045006000000001, 55.671535999999996, 24.082338, 46.349951999999995, 38.166196999999997, 15.777601000000001, 123.075288, 161.76140800000002, 12.053167, 60.597787000000004, 43.662361000000004, 45.789037999999998, 209.30117999999999, 32.190105000000003, 48.988551000000001, 55.191608000000002, 52.242056999999996, 89.343417000000002, 12.721064999999999, 109.08541600000001, 24.236315000000001, 19.817986000000001, 226.82451600000002, 100.985647, 60.686772999999995, 55.589548000000001, 69.965362999999996, 35.801557000000003, 25.728088, 16.169540999999999]
y_jvm2= [19.938967999999999, 178.796818, 67.512734999999992, 15.787599, 26.058038, 137.27913000000001, 12.535093, 59.649929999999998, 13.865891000000001, 60.618783000000001, 68.384602999999998, 283.39391599999999, 56.349432, 24.923209999999997, 44.113292999999999, 40.564831999999996, 12.393115, 120.76664, 152.30684499999998, 12.195145, 64.276227000000006, 18.565175999999997, 48.006701, 212.65967000000001, 32.544051000000003, 49.798428000000001, 58.516103000000001, 17.243377000000002, 92.973864999999989, 12.519096000000001, 111.39406500000001, 27.048887000000001, 20.014955999999998, 280.62933700000002, 86.977775999999992, 61.553642000000004, 50.455328000000002, 70.610264999999998, 28.390682999999999, 28.378685000000001, 17.351361000000001]
The problems with this generated pic above are that:
The label for x-aixs are too long, which are truncated(out of figure border).
Distict the bars by others instead of color. Since the pic will be print so that distinction by color would not be work. How to fill bars of one group with different style (e.g, the last bar infigure).
I will appreciate if anyone can help adjust the outlook of this pic. Thanks!
I would consider you clean up the names a little bit, that should help. Once you do that, you can change the rotation to 45 which will make it look better.
You can do that by changing plt.xticks(ind , axis, rotation=90) to plt.xticks("range", "custom label list", rotation=90)
def plotElapsedDis(axis, jvm1, jvm2, ylabel, title, name):
import matplotlib.pyplot as plt
import numpy as np
#fig, ax = plt.subplots(111)
fig = plt.figure()
ax = fig.add_subplot(111)
## the data
N = len(jvm1)
#menMeans = [18, 35, 30, 35, 27]
#womenMeans = [25, 32, 34, 20, 25]
ind = np.arange(N)+1
width = 0.25 # the width of the bars
# add "hatch"
rects1 = ax.bar(ind-width, jvm1, width, color='white', edgecolor='black', hatch="*")
rects2 = ax.bar(ind, jvm2, width, color='white', edgecolor='black', hatch='//')
ax.set_ylabel(ylabel)
ax.set_title(title)
plt.xticks(ind , axis, rotation=90)
ax.legend( (rects1[0], rects2[0]), ('Originl', 'Optimal') )
fig.tight_layout() # make sure it fits
plt.show()
plotElapsedDis(keys, y_jvm1, y_jvm2, 'seconds', 'CPU Elapsed', '../tmp/cpu_elapsed.jpg')

Categories

Resources