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()
Related
I'm plotting some data using sns.jointplot and I want the data inside the scatterplot to remain as points and the histograms on the side to be kde plots instead. I've tried using the kind='kde' argument, but this changes the data inside to not look like points in a scatterplot anymore. I've searched around for a bit and can't find how.
Here's my code for the plot:
plota = sns.jointplot( data = Hub_all_data, y = "Within module degree", x= "Participation coefficient", s=100, joint_kws=({'color':'green'}), marginal_kws=({'color': 'green'}))
plota.ax_joint.axvline(x=np.quantile(Pall,.25), color = "black", linestyle = "--")
plota.ax_joint.axvline(x=np.quantile(Pall,.75), color = "black", linestyle = "--")
plota.ax_joint.axhline(y=np.quantile(within_module_degree,.25), color = "black", linestyle = "--")
plota.ax_joint.axhline(y=np.quantile(within_module_degree,.75), color = "black", linestyle = "--")
plota.ax_marg_x.set_xlim(0, .6)
plota.ax_marg_y.set_ylim(-3, 2)
plota.set_axis_labels('P', 'Z', fontsize=16)
You could create a JointGrid and then plot the central and the marginal plots separately:
import seaborn as sns
import numpy as np
iris = sns.load_dataset('iris')
g = sns.JointGrid(data=iris, x="sepal_length", y="petal_length")
g.plot_joint(sns.scatterplot, s=100, color='green')
g.plot_marginals(sns.kdeplot, color='green', fill=True)
for q in np.quantile(iris['sepal_length'], [0.25, 0.75]):
for ax in (g.ax_joint, g.ax_marg_x):
ax.axvline(q, color="black", linestyle="--")
for q in np.quantile(iris['petal_length'], [0.25, 0.75]):
for ax in (g.ax_joint, g.ax_marg_y):
ax.axhline(q, color="black", linestyle="--")
pls I need to add a area color to my code to show a plot similar to this one bellow:
My code is here:
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
df = pd.DataFrame({'Time': [1,2,3,4,5],
'T=0': [0.5,0.16,0,0.25,0],
'T=2': [0.5,0.5,1,1,1],
'T=10': [0.75,0.8,0.85,0.9,0.8]
})
plt.plot( 'Time', 'T=10', data=df, marker='d', color='black', markersize=5, linewidth=1.5, linestyle=':')
plt.plot( 'Time', 'T=2', data=df, marker='^', color='black', markersize=4, linewidth=1.5,linestyle='--')
plt.plot( 'Time', 'T=0', data=df, marker='o', color='black', markersize=4, linewidth=1.5,linestyle='-')
plt.legend()
plt.xlabel("Time")
plt.xticks([1,2,3,4,5])
plt.xlim(0.9, 5.02)
plt.ylabel("Average")
plt.ylim(0, 1.02)
plt.show()
The actual result:
Many thanks.
All you need to do is add the following 3 lines to your code:
plt.fill_between(df['Time'], df['T=0'], alpha = 0.3, color = 'steelblue')
plt.fill_between(df['Time'], df['T=0'], df['T=2'], alpha = 0.3, color = 'yellow')
plt.fill_between(df['Time'], df['T=2'], df['T=10'], alpha = 0.3, color = 'red')
You can also create a legend corresponding to the colors. However, in the case of your graph, since two plot lines cross, it is best to leave the legend assigned to the plot lines rather than the colors (as you have).
I am trying to generate 3 boxplots side-by-side, each with different color.
The code below shows my attempt, but I am getting this unusual 'out of index' error.
It seems that index for the fliers for the 3rd boxplot is specified wrong, but I am not sure how to fix it, as I am trying to plot 3 boxplots side-by-sode
Could someone tell me how I can avoid this error?
Thank you,
from matplotlib.pyplot import (plot, savefig, xlim, figure,
ylim, legend, boxplot, setp,
axes, xlabel, ylabel, xticks,
axvline)
success_list_data=[[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.]]
# function for setting the colors of the box plots pairs
def setBoxColors(bp):
setp(bp['boxes'][0], color='red')
setp(bp['caps'][0], color='red')
setp(bp['caps'][1], color='red')
setp(bp['whiskers'][0], color='red')
setp(bp['whiskers'][1], color='red')
setp(bp['fliers'][0], color='red')
setp(bp['fliers'][1], color='red')
setp(bp['medians'][0], color='red')
setp(bp['boxes'][1], color='green')
setp(bp['caps'][2], color='green')
setp(bp['caps'][3], color='green')
setp(bp['whiskers'][2], color='green')
setp(bp['whiskers'][3], color='green')
setp(bp['fliers'][2], color='green')
setp(bp['fliers'][3], color='green')
setp(bp['medians'][1], color='green')
setp(bp['boxes'][2], color='purple')
setp(bp['caps'][4], color='purple')
setp(bp['caps'][5], color='purple')
setp(bp['whiskers'][4], color='purple')
setp(bp['whiskers'][5], color='purple')
setp(bp['fliers'][4], color='purple')
setp(bp['fliers'][5], color='purple')
setp(bp['medians'][2], color='purple')
def make_boxplots(success_list_data):
fig = figure()
ax = axes()
bp = boxplot(success_list_data, positions = [1, 2, 3], widths = 0.6)
setBoxColors(bp)
# label the x-ticks.
plt.xticks([1, 2, 3],
['Delta','Diag. Normal', 'Laplace'])
# label for the x-axis.
plt.xlabel('Guide Type')
# label for the y-axis.
plt.ylabel('Test Success Rate')
# this generates an error
>>> make_boxplots(success_list_data)
>>> Traceback (most recent call last):
File "<ipython-input-7-7d712300046b>", line 1, in <module>
make_boxplots(success_list_data)
File "<ipython-input-6-16ffa2fcfdd4>", line 37, in make_boxplots
setBoxColors(bp)
File "<ipython-input-6-16ffa2fcfdd4>", line 18, in setBoxColors
setp(bp['fliers'][3], color='green')
IndexError: list index out of range
Here is the code that will work without errors.
from matplotlib.pyplot import (plot, savefig, xlim, figure,
ylim, legend, boxplot, setp,
axes, xlabel, ylabel, xticks,
axvline)
# Need to import matplotlib.pyplot since you are using it below.
import matplotlib.pyplot as plt
success_list_data=[[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.]]
# function for setting the colors of the box plots pairs
def setBoxColors(bp):
setp(bp['boxes'][0], color='red')
setp(bp['caps'][0], color='red')
setp(bp['caps'][1], color='red')
setp(bp['whiskers'][0], color='red')
setp(bp['whiskers'][1], color='red')
setp(bp['fliers'][0], color='red')
setp(bp['fliers'][1], color='red')
setp(bp['medians'][0], color='red')
setp(bp['boxes'][1], color='green')
setp(bp['caps'][2], color='green')
setp(bp['caps'][3], color='green')
setp(bp['whiskers'][2], color='green')
setp(bp['whiskers'][3], color='green')
setp(bp['fliers'][2], color='green')
# setp(bp['fliers'][3], color='green')
setp(bp['medians'][1], color='green')
setp(bp['boxes'][2], color='purple')
setp(bp['caps'][4], color='purple')
setp(bp['caps'][5], color='purple')
setp(bp['whiskers'][4], color='purple')
setp(bp['whiskers'][5], color='purple')
# setp(bp['fliers'][4], color='purple')
# setp(bp['fliers'][5], color='purple')
setp(bp['medians'][2], color='purple')
def make_boxplots(success_list_data):
fig = figure()
ax = axes()
bp = boxplot(success_list_data, positions = [1, 2, 3], widths = 0.6)
setBoxColors(bp)
# label the x-ticks.
plt.xticks([1, 2, 3],
['Delta','Diag. Normal', 'Laplace'])
# label for the x-axis.
plt.xlabel('Guide Type')
# label for the y-axis.
plt.ylabel('Test Success Rate')
make_boxplots(success_list_data)
Here is the output of bp['fliers']:
[<matplotlib.lines.Line2D at 0x7fa8e0d41710>,
<matplotlib.lines.Line2D at 0x7fa8e0d52a10>,
<matplotlib.lines.Line2D at 0x7fa8e0d64cd0>]
Index of 3 and above will be out of index range.
This is the sine and cosine plot I draw using matplotlib. But the tick labels are below the plot and can hardly seen.
My python code is:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6), dpi=96)
plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="consine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$+\frac{\pi}{2}$', r'$+\pi$'])
plt.yticks([-1, 1],
[r'$-1$', r'$+1$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc='upper left', frameon=False)
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='green', edgecolor='None', alpha=0.2))
plt.savefig("figures/exercise10.png", dpi=120)
plt.show()
So, how should I set a tick label above a plot?
Thank you!
Possibly you want to set the labels and the axes spines on top of the lines. This can easily be achieved with the "axes.axisbelow" rcParam.
plt.rcParams["axes.axisbelow"] = False
I need log scale x-axis. Here is my code:
plt.bar(critical_pressures_reversed, mercury_volume_scaled, bottom = 0, log = True, linewidth=0, align="center",width=.1)
plt.title("Mercury intrusion", fontsize=20)
plt.xlabel("Critical Pressure $P_c \, [kPa]$", fontsize=16)
plt.ylabel("Mercury volume $V_m \, [\mu m^3]$", fontsize=16)
plt.grid(b=True, which='major', color='black', linestyle='-', linewidth=1)
plt.grid(b=True, which='minor', color='gray', linestyle='-', linewidth=0.15)
frame = plt.gca()
figure = plt.gcf()
frame.set_xscale('log')
frame.set_axisbelow(True)
figure.set_size_inches(12, 6)
plt.savefig("intrusion_6n_press.png", dpi=300, bbox_inches='tight')
plt.close()
Resulting plot:
How to force pyplot to draw bars with constant width?
I am using matplotlib (1.4.2)
You could use plt.fill but the bar width should change based on the log. For instance, for a random dataset, the following lines:
import matplotlib.pyplot as plt
import numpy as np
x, y = np.random.randint(1,51,10), np.random.randint(1,51,10)
width = 1e-2
for i in range(len(x)):
plt.fill([10**(np.log10(x[i])-width), 10**(np.log10(x[i])-width), 10**(np.log10(x[i])+width), 10**(np.log10(x[i])+width)],[0, y[i], y[i], 0], 'r', alpha=0.4)
plt.bar(x,y, bottom = 0, log = True, linewidth=0, align="center",width=.1, alpha=0.4)
will produce the figure below. Everything you need to do is to choose a proper width parameter.