ax.text2d in python (Matplotlib) - python

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'))

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.

Matplotlib: How to change the location of names?

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()

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()

How to print colorbar data from pick_event

for i in range(5):
for j in range(5):
sub_image = self.image[i*8:i*8+8, j*8:j*8+8]
ax = plt.subplot(gs[4 - i, j], picker = True, label = self.iD)
c = ax.pcolormesh(sub_image, vmin=0, vmax=maxZ, cmap="viridis")
ax.axis("off")
ax.set_aspect("equal")
self.grid[4-i,j] = self.iD
self.iD += 1
fig.subplots_adjust(right=0.71, left=.285, top=0.9, bottom=0.1)
self.cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
self.cbar = fig.colorbar(c, cax=self.cbar_ax)
self.cbar.set_label("Charge (Photoelectrons)", rotation=270, size=24, labelpad=24)
self.cbar_ax.tick_params(labelsize=15)
fig.suptitle(f"Run {self.run} Event {self.ev}", fontsize=30)
fig.canvas.mpl_connect("pick_event",self.nextWindow)
self.layout.addWidget(self.static_canvas,1,1)#,1,2)
self.toolBar = NavigationToolbar(self.static_canvas, self)
self.layout.addWidget(self.toolBar,2,1,1,2)
snapshot of plot
I am trying to create the functionality for when a pick_event is processed, the value that corresponds with the colorbar is printed. When the cursor is over any part of the plot, the NavigationToolbar2QT displays the value I want on the bottom right, but I dont know how to access it otherwise.
This is how I was able to access the data. I then formatted the string to get the data I want.
data = self.toolBar._mouse_event_to_message(event.mouseevent)

fetch the data once the user hover the mouse on a map

I use the geopandas to visualize the data in the map after I merge the goepandas data frame with the numeric data frame. I want to render this data once the user hover over the country that this data belongs to it .right now I mange to render the coordinate as annotation where the mouse is over but I need the data
enter code genertate() : Map_Figure, Map_Graph = plt.subplots()
dataset = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world = pd.DataFrame(dataset[['name', 'geometry', 'iso_a3']])
data2 = (records['Location'].value_counts()).reset_index()
data2.columns = ['name', 'Number']
data2['Number'] = data2['Number'].apply(int)
annot = Map_Graph.annotate("", xy=(0, 0), xytext=(20, 20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
datum = world.set_index('name').join(data2.set_index('name'))
World = geopandas.GeoDataFrame(datum)
#print(Map_Graph)
basePlot = World.plot(ax=Map_Graph, column='Number', linewidth=0.1, edgecolor='black', cmap='nipy_spectral',
vmin=World['Number'].min(), vmax=World['Number'].max(), legend=True)
# worldPlot= World.plot(ax=Map_Graph, color= 'white', edgecolor='black', cmap='tab10', scheme='QUANTILES', figsize=(8, 4))
locations = data2.values
box = []
for word, count in locations[:10]:
string = '%s | %s posts' % (word, human_format(count))
if len(string) >= 27:
string = string[:27] + " \n" + string[27:]
else:
string = string
box.append(string)
s = '\n'.join(box)
mapText = '%s ' % (s)
Map_Graph.text(-340, -80, mapText, size='small', wrap=True,
bbox={'boxstyle': 'round', 'facecolor': 'white', 'alpha': 0.5, 'pad': 0.8})
Map_Graph.set_axis_off()
Map_Figure.set_tight_layout(True)
Map_Figure.savefig("Report/data/Map.png")
mapCursor(Map_Graph)
Map_Figure.set_size_inches(6, 3.3)
return Map_Figure,basePlothere
and the fowling code to render the data where the mouse hover
enter code here
self.mapFigure,ax= AM.generate_Map()
#hover = HoverTool(tooltips=[('Country/region', '#country'), ('% obesity', '#per_cent_obesity')])
self.mapGraphs = FigureCanvasWxAgg(self.gPanel_map, -1, self.mapFigure)
datacursor(ax, xytext=(15, -15), bbox=dict(fc='white'), arrowprops=None, hover=True,
formatter='{x.d}: \n{y}'.format)

Categories