Matplotlib: How to change the location of names? - python

I have a function that reads a CSV file and outputs it to graphs. His window looks like this
As you can see, the names of the graphs Filter and step2 are on the left and all the others are on the right. This does not suit me. Here is my function
def Grahp2():
df = pd.read_csv('Dataset.csv',)
names = ['P', 'Filter', 'Answers', 'step','step2','Comulative', 'Delta_ema','ComulativePOC', 'Delta_P', 'Sum','SpeedUp', 'M' ]
features = df[names]
features.index = df['Time']
axs = features.plot(subplots=True)
cursor = MultiCursor(axs[1].get_figure().canvas, axs)
plt.subplots_adjust(wspace=0.19, hspace=0.05, top=0.99, right=0.988, bottom=0.052, left=0.055)
plt.show()
Is it possible just in my method to make sure that all the names are in one particular place?

def Grahp2():
df = pd.read_csv('Датасет с дельтами ема.csv',)
names = ['P', 'Filter', 'Answers', 'step','step2','Comulative', 'Delta_ema','ComulativePOC', 'Delta_P', 'Sum','SpeedUp', 'M' ]
features = df[names]
features.index = df['Время']
axs = features.plot(subplots=True)
axs[0].legend(loc = 'upper right')
axs[1].legend(loc = 'upper right')
axs[2].legend(loc = 'upper right')
axs[3].legend(loc = 'upper right')
axs[4].legend(loc = 'upper right')
axs[5].legend(loc = 'upper right')
axs[6].legend(loc = 'upper right')
axs[7].legend(loc = 'upper right')
axs[8].legend(loc = 'upper right')
axs[9].legend(loc = 'upper right')
axs[10].legend(loc = 'upper right')
axs[11].legend(loc = 'upper right')
cursor = MultiCursor(axs[1].get_figure().canvas, axs)
plt.subplots_adjust(wspace=0.19, hspace=0.05, top=1, right=1, bottom=0.045, left=0.033)
plt.show()

Related

Finding average of multiple lines in matplotlib

I am trying to create a graph that takes the averages from the below lines and plot them on the same new graph of the same nature.
fig, ax = plt.subplots(1,1, figsize=(10,12))
yticks = np.arange(nchan) * 0.2
lines_BC = plt.plot(resampled_BC.T + yticks[np.newaxis], label = "BC", c='black')
lines_CP = plt.plot(resampled_CP.T + yticks[np.newaxis], label = "CP", c='red')
lines_CR = plt.plot(resampled_CR.T + yticks[np.newaxis], label = "CR", c='cyan')
lines_DC = plt.plot(resampled_DC.T + yticks[np.newaxis], label = "DC", c='blue')
lines_JC = plt.plot(resampled_JC.T + yticks[np.newaxis], label = "JC", c='lime')
ax.set_yticks(yticks)
ax.set_yticklabels(muscles)
ax.set_ylabel('Muscles')
ax.set_xlabel('Time (ms)')
leg = ax.legend([lines_BC[0]] + [lines_CP[0]] + [lines_CR[0]] + [lines_DC[0]] + [lines_JC[0]], ['BC', 'CP', 'CR', 'DC', 'JC'], loc='upper right')
plt.show()
I have tried using np.mean but to no luck.

Animated/interactive plots for DBSCAN clustering

I have the code below. I'm trying to build an interactive DBSCAN clustering plot. When I run it, I get three plots but not interactive. Where is the problem in the code and how to fix it.
df_mv = pd.read_csv(r"https://raw.githubusercontent.com/HanaBachi/MachineLearning/main/multishape.csv") # load from Prof. Pyrcz's GitHub
df_mv.head()
text_trap = io.StringIO()
sys.stdout = text_trap
l = widgets.Text(value=' DBSCAN, Hana Bachi, The University of Texas at Austin',
layout=Layout(width='950px', height='30px'))
eps = widgets.FloatSlider(min=0, max = 2, value=0.1, step = 0.1, description = 'eps',orientation='horizontal', style = {'description_width': 'initial'}, continuous_update=False)
minPts = widgets.FloatSlider(min=0, max = 5, value=1, step = 1, description = 'minPts %',orientation='horizontal',style = {'description_width': 'initial'}, continuous_update=False)
color = ['blue','red','green','yellow','orange','white','magenta','cyan']
style = {'description_width': 'initial'}
ui = widgets.HBox([eps,minPts],)
ui2 = widgets.VBox([l,ui],)
# create activation function plots
def DBSCAN_plot(eps, minPts):
db = DBSCAN(eps=0.155, min_samples=5).fit(df_mv)
labels = db.labels_
# n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
# x = df_mv.values[:,0]
# y = df_mv.values[:,1]
# cmap = plt.cm.rainbow
#norm = mc.BoundaryNorm(labels, cmap.N)
plt.figure(figsize=(14,7))
plt.scatter(x, y, c=labels, cmap='tab10', s=50)
plt.scatter(x[np.where(labels==-1)], y[np.where(labels==-1)], c='k', marker='x', s=100)
plt.title('DBSCAN interactive plot', fontsize = 20)
plt.colorbar()
plt.show()
plt.subplots_adjust(left=0.0, bottom=0.0, right=2.0, top=1.0, wspace=0.2, hspace=0.3)
plt.show()
# create dashboard/formatting
uia = widgets.HBox([interactive_plot1],)
uia2 = widgets.VBox([eps, uia],)
uib = widgets.HBox([interactive_plot1],)
uib2 = widgets.VBox([minPts, uib],)
interactive_plot1 = widgets.interactive_output(DBSCAN_plot, {'eps': eps,'minPts':minPts})
interactive_plot1.clear_output(wait = True) #
How can I make this plot interactive in function of eps and minPts

ax.text2d in python (Matplotlib)

I am using text2d() to write some information on the bar3d-Diagram.
The piece of code is this one:
textstr = '\n'.join((
'{}'.format(langbezeichnung),
'Beprobung {} - {}'.format(datum_start, datum_end),
'{} Messstellen'.format(anzahl_mst_para),
"BG = {} µg/L".format(bestimmungsgrenze),
"75% SW = {} µg/L".format(warnwert),
"SW = {} µg/L".format(grenzwert)))
ax.text2D(0.645, 0.74, s=textstr, transform=ax.transAxes, fontsize=12, ha='left', va='top', bbox=dict(facecolor='white', alpha=1, edgecolor='black', linewidth=0.2, boxstyle='square'))
and the result is like that:
but i would like to have the equal signs ("=") at the same line.
Could anybody help me?
Thank you
Rabea
Use Monospace font and set the space. The spaces will align in this case. Example...
ax = plt.axes(projection='3d')
textstr = '\n'.join((
'{}'.format('langbezeichnung'),
'Beprobung {} - {}'.format('datum_start', 'datum_end'),
'{} Messstellen'.format('anzahl_mst_para'),
"BG = {} µg/L".format('bestimmungsgrenze'),
"75% SW = {} µg/L".format('warnwert'),
"SW = {} µg/L".format('grenzwert')))
ax.text2D(0.645, 0.74, s=textstr, family='monospace', transform=ax.transAxes, fontsize=12, ha='left', va='top', bbox=dict(facecolor='white', alpha=1, edgecolor='black', linewidth=0.2, boxstyle='square'))

Barplot subplot legend python

Hello everyone how can i make legend for 3 different bar color that code with subplot?
Data frame:
This is my code:
fig,axs = plt.subplots(2,3, figsize=(30,20))
axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color = ['lightsalmon','maroon','darkorange'])
axs[0,1].legend(['Low Tenure = x<24','Medium Tenure = 24<= x <=48','High Tenure = x >=48'],loc='best',fontsize=12)
plt.show()
And the result for barplot legend only shows 1 label like this:
Is there any solution to shows all of my legend?
Try this:
fig,axs = plt.subplots(2,3, figsize=(30,20))
axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color ['lightsalmon','maroon','darkorange'])
axs = axs[0,1]
lns1 = axs.plot('-',label = 'Low Tenure = x<24')
lns2 = axs.plot('-',label = 'Medium Tenure = 24<= x <=48')
lns3 = axs.plot('-',label = 'High Tenure = x >=48')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
axs.legend(lns, labs,loc=0)
plt.show()

Bar chart starting out of axis in python

I need to copy the bar chart in the image with python.
bar chart I have to copy
What I have been able to achieve is next image.
bar chart I have achieved
And the code I have used is:
import matplotlib.pyplot as plt
ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben
titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]
colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []
for i in range(len(euros)):
dummysum1.append(euros[i]+4000)
dummysum2.append(max(euros)+15000)
if euros[1] > 0:
dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
dummysum1[1] = 4000
position1 = (euros[0]+euros[2])/2
percentile = (euros[2]-euros[0])/euros[0]*100
if percentile > 0:
label0 = '+{:.1f}%'.format(percentile)
else:
label0 = '{:.1f}%'.format(percentile)
fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1])
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')
ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)
ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1], '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)
ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')
plt.show()
. How can I get the yellow bar chart starting at y=130386 instead of y=0 and the yellow arrow at the right hand side?
(The first question is the most important!)
Thank you all!
For the first question, just add a value for the bottom parameter. I have also added the arrow using annotate:
import matplotlib.pyplot as plt
ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben
titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]
colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []
for i in range(len(euros)):
dummysum1.append(euros[i]+4000)
dummysum2.append(max(euros)+15000)
if euros[1] > 0:
dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
dummysum1[1] = 4000
position1 = (euros[0]+euros[2])/2
percentile = (euros[2]-euros[0])/euros[0]*100
if percentile > 0:
label0 = '+{:.1f}%'.format(percentile)
else:
label0 = '{:.1f}%'.format(percentile)
fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1], bottom=ausgaben)
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')
ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)
ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1]+ausgaben, '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)
ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')
ax.annotate("", xy=(2.5, ausgaben+profit*1.05), xytext=(2.5, ausgaben), arrowprops=dict(arrowstyle="->", color="orange", lw=2.0))
plt.show()

Categories