Polar plot xtick label position - python

I have a function, which produces polar plot with matplotlib.
from math import pi
import matplotlib as mpl
import matplotlib.pyplot as plt
first_arg = {
'Introversion': 17, 'Intuition': 34, 'Feeling': 29, 'Perceiving': 18,
'Extraversion': 27, 'Sensing': 25, 'Thinking': 23, 'Judging': 16
}
second_arg = {
'Introversion': 16, 'Intuition': 25, 'Feeling': 31, 'Perceiving': 15,
'Extraversion': 22, 'Sensing': 29, 'Thinking': 23, 'Judging': 23
}
def plot_scales_chart(*args):
scales = [
'Introversion', 'Intuition', 'Feeling', 'Perceiving',
'Extraversion', 'Sensing', 'Thinking', 'Judging'
]
angles = [n / float(len(scales)) * 2 * pi for n in range(len(scales))]
angles += angles[:1]
mpl.use('agg')
ax = plt.subplot(polar=True)
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)
plt.xticks(angles[:-1], scales)
ax.set_rlabel_position(0)
plt.yticks([15, 25], ["15", "25"], color="grey", size=8)
plt.ylim(0, 35)
colors = ['#5159be', '#86e5c7']
for i, arg in enumerate(args):
values = []
for scale in scales:
values.append(arg[scale])
values += values[:1]
ax.plot(angles, values, alpha=0.7, color=colors[i], linewidth=0, linestyle='solid')
ax.fill(angles, values, colors[i], alpha=0.7)
plt.savefig('chart.png')
I want to move xaxis labels so as not to cross the circle.
How to set label position of particularly one scale or is that possible to move all labels further from the center? What is the best practice there?

You can use ax.tick_params to add padding to move the labels 'away' from the center. Adding the line ax.tick_params(axis='x', which='major', pad=15) after you set the xticks in plt.xticks() does the trick.
from math import pi
import matplotlib as mpl
import matplotlib.pyplot as plt
first_arg = {
'Introversion': 17, 'Intuition': 34, 'Feeling': 29, 'Perceiving': 18,
'Extraversion': 27, 'Sensing': 25, 'Thinking': 23, 'Judging': 16
}
second_arg = {
'Introversion': 16, 'Intuition': 25, 'Feeling': 31, 'Perceiving': 15,
'Extraversion': 22, 'Sensing': 29, 'Thinking': 23, 'Judging': 23
}
def plot_scales_chart(*args):
scales = [
'Introversion', 'Intuition', 'Feeling', 'Perceiving',
'Extraversion', 'Sensing', 'Thinking', 'Judging'
]
angles = [n / float(len(scales)) * 2 * pi for n in range(len(scales))]
angles += angles[:1]
mpl.use('agg')
ax = plt.subplot(polar=True)
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)
plt.xticks(angles[:-1], scales)
ax.tick_params(axis='x', which='major', pad=15)
ax.set_rlabel_position(0)
plt.yticks([15, 25], ["15", "25"], color="grey", size=8)
plt.ylim(0, 35)
colors = ['#5159be', '#86e5c7']
for i, arg in enumerate(args):
values = []
for scale in scales:
values.append(arg[scale])
values += values[:1]
ax.plot(angles, values, alpha=0.7, color=colors[i], linewidth=0, linestyle='solid')
ax.fill(angles, values, colors[i], alpha=0.7)
plt.savefig('chart.png')

Related

Output Values from Regression Line inside Matplotlib window

import matplotlib.pyplot as plt
import numpy as np
x = np.array([6, 15, 24, 33, 41, 52, 59, 66, 73, 81])
y = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
coef = np.polyfit(x, y, 1)
poly1d_fn = np.poly1d(coef) # to create a linear function with coefficients
plt.plot(x, y, 'ro', x, poly1d_fn(x), '-b')
plt.errorbar(x, poly1d_fn(x), yerr=poly1d_fn(x) - y, fmt='.k')
plt.show()
I have a working code which produces based upon my input a graph with error bars and the regression line. That's all fine. Now what I wanted to do is add a text box below and once a user inputs a number, e.g. 12 it outputs the according value (re regression line).
left, bottom, width, height = 0.15, 0.02, 0.7, 0.10
plt.subplots_adjust(left=left, bottom=0.25) # Make space for the slider
input_field = plt.axes([left, bottom, width, height])
box = TextBox(input_field, 'value')
I tried it with this approach. Though being unsuccessful: I can't get it to take a value and output it on the GUI interface matplotlib provides. The field would need to be checked for every input. Matplotlib offers on_text_change(self, func)or on_submit(self, func), so that might be working - but how to output?
Does anyone have an idea?
I would use a simple Text artist to display the result. But being fancy, I would also display lines on the graph showing the input and output values.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([6, 15, 24, 33, 41, 52, 59, 66, 73, 81])
y = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
coef = np.polyfit(x, y, 1)
poly1d_fn = np.poly1d(coef) # to create a linear function with coefficients
def submit(val):
try:
x = float(val)
y = poly1d_fn(x)
ax.annotate('', xy=(x,0), xycoords=('data','axes fraction'),
xytext=(x,y), textcoords='data',
arrowprops=dict(arrowstyle='-', ls='--'))
ax.annotate(f'{x:.2f}', xy=(x,0), xycoords=('data','axes fraction'))
ax.annotate('', xy=(0,y), xycoords=('axes fraction','data'),
xytext=(x,y), textcoords='data',
arrowprops=dict(arrowstyle='-', ls='--'))
ax.annotate(f'{y:.2f}', xy=(0,y), xycoords=('axes fraction','data'))
output_box.set_text(f'Result = {y:.2f}')
plt.draw()
except ValueError:
pass
fig, ax = plt.subplots()
ax.plot(x, y, 'ro', x, poly1d_fn(x), '-b')
ax.errorbar(x, poly1d_fn(x), yerr=poly1d_fn(x) - y, fmt='.k')
left, bottom, width, height, pad = 0.15, 0.02, 0.3, 0.10, 0.1
fig.subplots_adjust(left=left, bottom=0.25) # Make space for the slider
input_field = fig.add_axes([left, bottom, width, height])
text_box = matplotlib.widgets.TextBox(input_field, 'value')
text_box.on_submit(submit)
output_box = fig.text(left+width+pad, bottom+height/2, s='Result = ', va='center')

Mathplotlib pandas-Plotting average line to scatter plot?

I have a scatter plot created from two columns of a pandas data frame and I would like to add a line across each axis representing the average. Is this possible with a scatter plot?
plt.title("NFL Conversion Rates", fontsize=40)
# simulating a pandas df['team'] column
types = df.Tm
x_coords = df['3D%']
y_coords = df['4D%']
binsy = [15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85]
binsx = [30,35,40,45,50,55]
avg_y = y_coords.mean()
avg_y = round(avg_y, 1)
display(avg_y)
avg_x = x_coords.mean()
avg_x = round(avg_x, 1)
display(avg_x)
for i,type in enumerate(types):
x = x_coords[i]
y = y_coords[i]
plt.scatter(x, y, s=30, marker='o', edgecolor='black', cmap='purple', linewidth=1, alpha = 0.5)
plt.text(x+0.2, y+0.1, type, fontsize=14)
plt.xlabel('3rd Down Conversion Percentage',fontsize=30)
plt.ylabel('4th Down Conversion Percentage', fontsize=30)
plt.xticks(binsx)
plt.yticks(binsy)
You can try
plt.axvline(<value>,color='red',ls='--') and plt.axhline(<value>,color='red',ls='--'). Substitute with the value at which you want the lines

Showing two data sets of `ax2.set_xticklabels` in a subplot

I have an upper subplot that shows two data sets: orange and green.
The following code shows the xtick labels of the green data set,
in the ax2 axis of the upper subplot (axis labelled as X2 in the figure):
ind_pos_Pd3 = [0, 4, 8, 12, 16]
axarr[0].set_xticks(X1_green[ind_pos_Pd3])
ax2.set_xticks(X1_green[ind_pos_Pd3])
ax2.set_xticklabels(["%.2f" % i for i in X2_green[ind_pos_Pd3]])
On the contrary, the following code shows the the xtick labels of the orange data set,
in the ax2 axis of the upper subplot (axis labelled as X2 in the figure):
ind_pos_Bd3 = [0, 4, 8, 12, 16, 20, 24, 28, 32]
axarr[0].set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticklabels(["%.2f" % i for i in X2_orange[ind_pos_Bd3]])
Is there a way to "mix" both schemes and achieve a ax2 axis divided into two panels: the "lower panel" is filled with the labels from the green data set, and the "upper panel" is filled with the labels from the orange data set ?
Something like:
I was thinking on this pseudo-code:
ind_pos_Bd3 = [0, 4, 8, 12, 16, 20, 24, 28, 32]
ind_pos_Pd3 = [0, 4, 8, 12, 16]
axarr[0].set_xticks(X1_orange[ind_pos_Bd3])
axarr[0].set_xticks(X1_green[ind_pos_Pd3])
ax2.set_xticks(X1_green[ind_pos_Pd3])
ax2.set_xticklabels(["%.2f \n %.2f" % i for i in zip(X2_orange[ind_pos_Bd3], X1_green[ind_pos_Pd3]])
However, the "%.2f \n %.2f" scheme is not working.
Minimal working example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
X1_orange = np.array([ 10., 30.1, 50.2, 70.3, 90.4, 110.51, 130.61, 150.71, 170.81,
190.91, 211.01, 231.11, 251.21, 271.31, 291.41, 311.52, 331.62, 351.72,
371.82, 391.92, 412.02, 432.12, 452.22, 472.32, 492.42, 512.53, 532.63,
552.73, 572.83, 592.93, 613.03, 633.13, 653.23])
X2_orange = np.array([ 2.56691976, 2.5781089 , 2.59624855, 2.62275805, 2.64568568, 2.66607658,
2.6959714 , 2.7231501 , 2.75529391, 2.78894345, 2.81573712, 2.84711104,
2.88437499, 2.9191375 , 2.95033337, 2.99340594, 3.02206115, 3.06383265,
3.08649135, 3.12707204, 3.18500195, 3.24240915, 3.25965166, 3.36137181,
3.35468811, 3.42661704, 3.46254097, 3.61136855, 3.65505401, 3.89043407,
3.80421353, 3.79380128, 4.01570509])
X1_green = np.array([ 10. , 30.1 , 50.2 , 70.3 , 90.4 , 110.51, 130.61, 150.71, 170.81,
190.91, 211.01, 231.11, 251.21, 271.31, 291.41, 311.52, 331.62])
X2_green = np.array([ 1.9894731 , 2.00259207, 2.01875725, 2.04333825, 2.07700656, 2.09629866,
2.14727031, 2.17488234, 2.2499103 , 2.2698862 , 2.31607409, 2.41452705,
2.50847008, 2.61117044, 2.70657103, 3.25283819, 3.31585812])
Y0_orange = np.array([-1.87483583, -1.82358431, -1.78627169, -1.75242213, -1.7299256 , -1.69363695,
-1.64623615, -1.59656948, -1.56967972, -1.55058869, -1.51874314, -1.45673839,
-1.40554361, -1.39904184, -1.35322104, -1.33906865, -1.30865871, -1.28099683,
-1.24897269, -1.19802619, -1.17268543, -1.13523614, -1.09290541, -1.05642197,
-1.00189406, -0.95390527, -0.90890049, -0.82522042, -0.76334378, -0.64504498,
-0.62782754, -0.47358849, -0.49772039])
Y0_green = np.array([-1.97113854, -1.92908192, -1.84404067, -1.75333855, -1.67575628, -1.58010168,
-1.48746063, -1.40770641, -1.31802444, -1.2302243 , -1.14927205, -1.04251178,
-0.91661452, -0.82924669, -0.65075739, -0.37715382, -0.21349827])
##### THREE SUBPLOTS::
###### Y0 plot:
f, axarr = plt.subplots(3, sharex=True, figsize=(11,5))
axarr[0].plot(X1_orange, Y0_orange, linestyle='--', marker="o", markersize=6, color='orange')
axarr[0].plot(X1_green, Y0_green, linestyle='--', marker="o", markersize=6, color='green')
axarr[0].set_ylabel('Y0', fontsize=15)
# Create a new axis:
axarr[0].grid()
ax2 = axarr[0].twiny()
# Make the ax1-ticks and ax1-tick-labels match the line color (blue):
axarr[0].tick_params('x', colors='blue')
# Make the ax2-ticks and ax2-tick-labels match the red color:
# this only controls the font and color of label
ax2.set_xlabel('x2', fontsize=14, color='red')
# this also adds the numbers on top of the tics,
# but sets the colors of the tics
ax2.tick_params('x', colors='orange')
# Set xlimits of ax2 the same as ax1
ax2.set_xlim(axarr[0].get_xlim())
# Set ticks at desired position
ind_pos_Bd3 = [0, 4, 8, 12, 16, 20, 24, 28, 32]
axarr[0].set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticklabels(["%.2f" % i for i in X2_orange[ind_pos_Bd3]])
#ind_pos_Pd3 = [0, 4, 8, 12, 16]
#axarr[0].set_xticks(X1_green[ind_pos_Pd3])
#ax2.set_xticks(X1_green[ind_pos_Pd3])
#ax2.set_xticklabels(["%.2f" % i for i in X2_green[ind_pos_Pd3]])
# Just to align the Delta_V ylabel to the other 3 ylabel's
labelx = -0.075 # very close to the plot
axarr[0].yaxis.set_label_coords(labelx, 0.5, transform=None)
##### Y1 plot:
#f, axarr = plt.subplots(3, sharex=True)
axarr[1].set_ylabel('Y1', fontsize=15)
# Create a new axis:
axarr[1].grid()
ax2 = axarr[1].twiny()
# Make the ax1-ticks and ax1-tick-labels match the line color (blue):
axarr[1].tick_params('x', colors='blue')
# Make the ax2-ticks and ax2-tick-labels match the red color:
ax2.tick_params('x', colors='red')
ax2.set_xticklabels([]) # disable the tic labels
# Set xlimits of ax2 the same as ax1
ax2.set_xlim(axarr[1].get_xlim())
# Set ticks at desired position
ind_pos_Bd3 = [0, 4, 8, 12, 16, 20, 24, 28, 32]
axarr[1].set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticks(X1_orange[ind_pos_Bd3])
# Label ticks of ax2 with values from X2
#ax2.set_xticklabels(["%.2f" % i for i in P])
axarr[1].yaxis.set_major_formatter(mtick.FormatStrFormatter('%1.e'))
#### Y2 plot:
axarr[2].set_ylabel('Y2', fontsize=15)
# Create a new axis:
axarr[2].grid()
ax2 = axarr[2].twiny()
# Make the ax1-ticks and ax1-tick-labels match the line color (blue):
axarr[2].tick_params('x', colors='blue')
# Make the ax2-ticks and ax2-tick-labels match the red color:
axarr[2].set_xlabel('X1', fontsize=14, color='blue')
# this also adds the numbers on top of the tics,
# but sets the colors of the tics
axarr[2].tick_params('x', colors='blue')
# Make the ax2-ticks and ax2-tick-labels match the red color:
ax2.tick_params('x', colors='red')
ax2.set_xticklabels([]) # disable the tic labels
# Set xlimits of ax2 the same as ax1
ax2.set_xlim(axarr[2].get_xlim())
# Set ticks at desired position
ind_pos_Bd3 = [0, 4, 8, 12, 16, 20, 24, 28, 32]
axarr[2].set_xticks(X1_orange[ind_pos_Bd3])
ax2.set_xticks(X1_orange[ind_pos_Bd3])
# Label ticks of ax2 with values from X2
axarr[2].yaxis.set_major_formatter(mtick.FormatStrFormatter('%1.e'))
plt.show()
The trick is to add a new twin axis for each row of tick labels you want.
You can then position them properly setting the pad parameter in tick_params.
Allow me to make your example a little smaller so it's easier to follow
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
fig, ax = plt.subplots(figsize=(12,2))
np.random.seed(42)
x0 = np.arange(50)
y0 = np.random.rand(50)
x1 = np.arange(30)
y1 = np.random.rand(30) + 0.7
ax.plot(x0, y0, ls='--', marker='o', ms=6, color='orange')
ax.grid(True)
ax.tick_params('x', colors='blue')
ax.set_xlabel('x1', fontsize=14, color='blue')
ax.set_ylabel('y', fontsize=14)
tax1 = ax.twiny()
tax1.set_xlim(ax.get_xlim())
tax1.tick_params('x', colors='orange', pad=14)
tax1.set_xlabel('x2', fontsize=14, color='red', labelpad=6)
tax2 = ax.twiny()
tax2.set_xlim(ax.get_xlim())
tax2.plot(x1, y1, ls='--', marker='o', ms=6, color='green')
tax2.tick_params('x', colors='green')
tax2.set_xticks([0, 10, 20, 30])
fig.savefig('img.png', pad_inches=0, bbox_inches='tight')
As you pointed out in the comments an issue with this plot is that you get green and orange tick lines and you would like to have them in red just like the x2 label.
You can hide the green tick lines setting length=0 in tick_params, draw the orange plot ticks in red first and then set labels color to orange.
Here's the modified code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
fig, ax = plt.subplots(figsize=(12,2))
np.random.seed(42)
x0 = np.arange(50)
y0 = np.random.rand(50)
x1 = np.arange(30)
y1 = np.random.rand(30) + 0.7
ax.plot(x0, y0, ls='--', marker='o', ms=6, color='orange')
ax.grid(True)
ax.tick_params('x', colors='blue')
ax.set_xlabel('x1', fontsize=14, color='blue')
ax.set_ylabel('y', fontsize=14)
tax1 = ax.twiny()
tax1.set_xlim(ax.get_xlim())
tax1.tick_params('x', colors='red', pad=14)
tax1.set_xlabel('x2', fontsize=14, color='red', labelpad=6)
[x.set_color("orange") for x in tax1.get_xticklabels()]
tax2 = ax.twiny()
tax2.set_xlim(ax.get_xlim())
tax2.plot(x1, y1, ls='--', marker='o', ms=6, color='green')
tax2.tick_params('x', colors='green', pad=6, length=0)
tax2.set_xticks([0, 10, 20, 30])
fig.savefig('img2.png', pad_inches=0, bbox_inches='tight')

Python: Plt bar plot - different colors

In Python, how can I make the 'reported' bars green, and 'UNREPORTED' bars red?
I want to give different color to each of the reported and UNREPORTED bars in my graph.
new = (('AXIN', 37, 'reported'),
('LGR', 30, 'UNREPORTED'),
('NKD', 24, 'reported'),
('TNFRSF', 23, 'reported'),
('CCND', 19, 'reported'),
('APCDD', 18, 'reported'),
('TRD', 16, 'reported'),
('TOX', 15, 'UNREPORTED'),
('LEF', 15, 'reported'),
('MME', 13, 'reported'))
#sort them as most common gene comes first
new = sorted(new, key=lambda score: score[1], reverse=True)
#X, Y zip of the tuple new are for plt.bar
X, Y, _ = zip(*new)
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize = (20, 10))
mytitle = "Most common genes coexpressed with {gene1}, {gene2}, {gene3}, {gene4}".format(
gene1="Axin2", gene2="Lef", gene3="Nkd1", gene4="Lgr5")
plt.title(mytitle, fontsize=40)
plt.ylabel('Number of same gene encounters across studies', fontsize=20)
ax = plt.bar(range(len(X)), Y, 0.6, tick_label = X, color="green")
ax = plt.xticks(rotation=90)
new = tuple(new)
You can iterate over the bars and check if for the given index, the report is 'UNREPORTED'. If this is the case, colorize the bar using set_color.
import seaborn as sns
import matplotlib.pyplot as plt
new = (('AXIN', 37, 'reported'),
('LGR', 30, 'UNREPORTED'),
('NKD', 24, 'reported'),
('TNFRSF', 23, 'reported'),
('CCND', 19, 'reported'),
('APCDD', 18, 'reported'),
('TRD', 16, 'reported'),
('TOX', 15, 'UNREPORTED'),
('LEF', 15, 'reported'),
('MME', 13, 'reported'))
#sort them as most common gene comes first
new = sorted(new, key=lambda score: score[1], reverse=True)
#X, Y zip of the tuple new are for plt.bar
X, Y, rep = zip(*new)
plt.figure(figsize = (8, 6))
mytitle = "Most common genes coexpressed with {gene1}, {gene2}, {gene3}, {gene4}".format(
gene1="Axin2", gene2="Lef", gene3="Nkd1", gene4="Lgr5")
plt.title(mytitle)
plt.ylabel('Number of same gene encounters across studies')
bars = plt.bar(range(len(X)), Y, 0.6, tick_label = X, color="green")
plt.xticks(rotation=90)
for i, bar in enumerate(bars):
if rep[i] == 'UNREPORTED':
bar.set_color("red")
plt.show()
You need to pass a list or tuple of colors instead of just 1 color to plt.bar. You can do so by creating a color dictionary, then building the list of color.
new = sorted(new, key=lambda score: score[1], reverse=True)
# save the reporting type as R
X, Y, R = zip(*new)
# create color dictionary
color_dict = {'reported':'green', 'UNREPORTED':'red'}
plt.figure(figsize = (20, 10))
mytitle = "Most common genes coexpressed with {gene1}, {gene2}, {gene3}, {gene4}".format(
gene1="Axin2", gene2="Lef", gene3="Nkd1", gene4="Lgr5")
plt.title(mytitle, fontsize=40)
plt.ylabel('Number of same gene encounters across studies', fontsize=20)
# build the colors from the color dictionary
ax = plt.bar(range(len(X)), Y, 0.6, tick_label = X, color=[color_dict[r] for r in R])

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