Plot multiple lines in a loop - python

I try to plot lines in a loop,but its connecting it,i tried many variants,but cand understand and find the answer,maybe the dataframe
im a newbie in Matplotlib
the code of method:
self.testnewnewventnest[Debit] - is a nested dict with the data i need for plotting
def showmainplot(self):
for Debit in self.Debitlist:
self.Presinit = self.VentTable.loc[Debit]
self.Tinit= float(self.Tinit)
self.Presinit=int(float(self.Presinit))
self.Powinit = float(self.Powinit)
x = symbols("x")
for Turatie in self.Tfin:
eqPres = (Turatie/self.Tinit)*(Turatie/self.Tinit)*self.Presinit-x
PresFin = solve(eqPres)
eqDebit = (Turatie/self.Tinit)*int(Debit)
DebitFin = solve(eqDebit)
eqPow = (Turatie/self.Tinit)*(Turatie/self.Tinit)*(Turatie/self.Tinit)*float(self.Powinit)
self.TestnewVentnest['KW'] = float(eqPow)
self.TestnewVentnest['Turatie'] = Turatie
self.TestnewVentnest['Presiune'] = float(PresFin[0])
self.TestnewVent[float(eqDebit)] = dict(self.TestnewVentnest)
self.testnewnewventnest[Debit] = dict(self.TestnewVent)
print(self.testnewnewventnest)
axeslist = []
n=0
fig, ax = plt.subplots(figsize=(5, 5))
ax1 = ax.twinx()
ax1.spines.right.set_position(("axes", 1.06))
ax.set_xlabel("Debit")
for dicts in self.testnewnewventnest:
Ventdataframe = pd.DataFrame(self.testnewnewventnest[dicts])
print(Ventdataframe)
ax2 = plt.subplot()
fig, ax = plt.subplots(figsize=(5, 5))
ax1 = ax.twinx()
ax1.spines.right.set_position(("axes", 1.06))
ax.set_xlabel("Debit")
axeslist.append(plt.subplot())
# print(df.iloc[0])
# ax1.set_ylabel("Turatie")
# ax.set_ylabel("Presiune")
# Ventdataframe.plot(Ventdataframe.loc["Presiune"], color="b",label="Presiune"+str(n),marker = 'o')
Ventdataframe.loc["Presiune"].plot(color="b",label="Presiune"+str(n),marker = 'o')
n+=1
# ax2 = ax.twinx()
# ax2.set_ylabel('KW')
# ax1.plot(Ventdataframe.loc["Turatie"],color='#000000',label="Turatie",marker = 'o')
# ax2.plot(Ventdataframe.loc["KW"], color='r',label="KW",marker = 'o')
# ax1.grid()
# ax2.yaxis.set_major_locator(FixedLocator(Ventdataframe.loc["KW"]))
# ax.yaxis.set_major_locator(FixedLocator(Ventdataframe.loc["Presiune"]))
# ax1.yaxis.set_major_locator(FixedLocator(self.Tfin))
# ax.xaxis.set_major_locator(FixedLocator(Ventdataframe.columns))
# lc = matpl.ticker.NullLocator()
# ax.yaxis.set_major_locator(lc)
plt.show()
and the self.testnewnewventnest look like:
Yes,the problem was in the loop,and in the dictionaries,in every iteration he added all previous dictionaries from iterations

I would put that in a dataframe and do it like this.
uniques = df['ID'].unique()
for i in uniques:
fig, ax = plt.subplots()
fig.set_size_inches(4,3)
df_single = df[df['ID']==i]
sns.lineplot(data=df_single, x='Month', y='Expense')
ax.set(xlabel='Time', ylabel='Total Expense')
plt.xticks(rotation=45)
plt.show()

Related

overlay interaction visual in python

I want to visualize the interactions between two data's. Original (green) and prediction (brown). The length of the top line is from 200 to -20 and bottom from -20 to 200.
For the above table, I want to visualize in the below format
code I have tried so far
def newline(p1, p2, color='black'):
ax = plt.gca()
fig, ax = plt.subplots(1,1,figsize=(5,5), dpi= 60)
ax.hlines(y=1, xmin=-20, xmax=200, color='black', alpha=0.7)
ax.hlines(y=1.1, xmin=-20, xmax=200, color='black', alpha=0.7)
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = True
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
ax.yaxis.set_visible(False)
plt.box(False)
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
def newline(p1, p2, color='black'):
ax = plt.gca()
df = pd.read_excel('visual.xlsx', sheet_name='Sheet2')
prediction_list = df['prediction'].tolist()
originale_list = df['original'].tolist()
result_prediction = []
result_original = []
for i in range(len(prediction_list)):
temp = []
test = prediction_list[i].split('&')
for j in range(len(test)):
temp = []
temp.append(200 - int(test[j].split(':')[0]))
temp.append(int(test[j].split(':')[1]))
result_prediction.append(temp)
for i in range(len(originale_list)):
temp = []
test = originale_list[i].split('&')
for j in range(len(test)):
temp = []
temp.append(200 - int(test[j].split(':')[0]))
temp.append(int(test[j].split(':')[1]))
result_original.append(temp)
fig, ax = plt.subplots(1,1,figsize=(20,5), dpi= 60)
ax.hlines(y=1, xmin=200, xmax=-20, color='black', alpha=0.7)
ax.hlines(y=2, xmin=200, xmax=-20, color='black', alpha=0.7) -20')
for i in range(len(result_prediction)):
plt.plot(result_prediction[i], [2, 1], color='brown')
for i in range(len(result_original)):
plt.plot(result_original[i], [2, 1], color='green')
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = True
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
ax.yaxis.set_visible(False)
plt.box(False)
plt.savefig('test.png')
plt.show()
That will be help you.
Thanks

matplotlib-axis-with-two-scales-shared-origin

Matplotlib axis with two scales shared origin
I have already tried to implement this the existing stackflow solution and my both x-axes are not aligning to 0.
My Code :
def align_xaxis(ax1, v1, ax2, v2):
"""adjust ax2 xlimit so that v2 in ax2 is aligned to v1 in ax1"""
x1, _ = ax1.transData.transform((v1, 0))
x2, _ = ax2.transData.transform((v2, 0))
inv = ax2.transData.inverted()
dx, _ = inv.transform((0, 0)) - inv.transform((x1-x2, 0))
minx, maxx = ax1.get_xlim()
ax2.set_xlim(minx+dx, maxx+dx)
def unrealized_profit_loss_graph(profit_loss):
plt.style.use('ggplot');
fig = plt.figure()
ax1 = fig.add_subplot(111);
ax2 = ax1.twiny()
profit_loss['total_G/l'].
plot(kind='barh',color=profit_loss.positive.map({True: 'g', False: 'r'}))
profit_loss['gain_loss_perc'].plot(kind='barh',color=profit_loss.positive.map({True: 'b', False: 'y'}))
ax1.set_xlabel('%', fontsize=12)
ax2.set_xlabel('$', fontsize=12);
align_xaxis(ax1,0,ax2,0)
plt.xlim(-5000, 20000)
plt.xticks(rotation=45);
plt.show();
I would like both x axes to align at 0.
Also to show the negative plus the positive of the ax1.
Working example :
def unrealized_profit_loss():
Profit_loss = Path("C:/Users/champ/Documents/Pers/Python/stock_dfs/Profit_loss_tranactions.xlsx")
df = pd.read_excel(Profit_loss, sheet_name='Unrealized')
current_prices_ROTH=price_data_ROTH.loc[price_data_ROTH.index[-1]] current_prices_Personal=price_data_Personal.loc[price_data_Personal.index[-1]]
df2 = pd.DataFrame({'Symbol':current_prices_ROTH.index, 'Prices':current_prices_ROTH.values})
df2 = pd.DataFrame({'Symbol':current_prices_Personal.index, 'Prices':current_prices_Personal.values})
da= pd.merge(df,df2, how='left',on=['Symbol','Symbol'])
da['gain_loss_perc']=round(((da['Prices']-da['Cost/share'])/da['Cost/share'])*100,2)
da['total_G/l']=round((da['Prices']*da['Quantity'])-(da['Cost Basis']),0)
da['Account_symbol'] = str(da['Account'])
da['Account_symbol'] = da.agg(lambda x: f"{x['Symbol']} - {x['Account']}", axis=1)
da = da.sort_values(by=['total_G/l'],ascending=True)
da.index = da['Account_symbol']
da['positive'] = da['total_G/l'] > 0
del da.index.name
return(da)
def unrealized_profit_loss_graph(profit_loss):
# graph the profit and loss
#fig, (ax1,ax2) = plt.subplots(1,2,sharex=False,sharey=True,figsize=(16,8));
#fig, ax1 = plt.subplots(1,1,figsize=(16,8));
plt.style.use('ggplot');
fig = plt.figure()
ax1 = fig.add_subplot(111);
ax1.set_title('Total G/L (UNREALIZED - IN THE MARKET)');
#ax1 = fig.add_subplot() # Create matplotlib axes
ax2 = ax1.twiny()
profit_loss['total_G/l'].plot(kind='barh',color=profit_loss.positive.map({True: 'g', False: 'r'}))
profit_loss['gain_loss_perc'].plot(kind='barh',color=profit_loss.positive.map({True: 'b', False: 'y'}))
ax1.set_xlabel('%', fontsize=12);
ax2.set_xlabel('$', fontsize=12);
plt.xlim(-5000, 20000);
plt.xticks(rotation=45);
align_xaxis(ax1,0,ax2,0);
plt.show();
# Profit and loss
profit_loss = unrealized_profit_loss()
p_l = unrealized_profit_loss_graph(profit_loss)
xls file I read from
You failed to provide a working example. Nevertheless, try the following: Pass the respective axis to the plot function and then try aligning
def unrealized_profit_loss_graph(profit_loss):
plt.style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(111)
profit_loss['total_G/l'].plot(kind='barh',
color=profit_loss.positive.map({True: 'g', False: 'r'}),
ax=ax1)
ax2 = ax1.twiny()
profit_loss['gain_loss_perc'].plot(kind='barh',
color=profit_loss.positive.map({True: 'b', False: 'y'}),
ax=ax2)
ax1.set_xlabel('%', fontsize=12)
ax2.set_xlabel('$', fontsize=12)
plt.xlim(-5000, 20000)
plt.xticks(rotation=45)
align_xaxis(ax1,0,ax2,0)
plt.show();

Using Hlines ruins legends in Matplotlib

I'm struggling to adjust my plot legend after adding the axline/ hline on 100 level in the graph.(screenshot added)
if there's a way to run this correctly so no information will be lost in legend, and maybe add another hline and adding it to the legend.
adding the code here, maybe i'm not writing it properly.
fig, ax1 = plt.subplots(figsize = (9,6),sharex=True)
BundleFc_Outcome['Spend'].plot(kind = 'bar',color = 'blue',width = 0.4, ax = ax1,position = 1)
#
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('SPEND', color='b', size = 18)
ax1.set_xlabel('Bundle FC',color='w',size = 18)
ax2 = ax1.twinx()
ax2.set_ylabel('ROAS', color='r',size = 18)
ax1.tick_params(axis='x', colors='w',size = 20)
ax2.tick_params(axis = 'y', colors='w',size = 20)
ax1.tick_params(axis = 'y', colors='w',size = 20)
#ax1.text()
#
ax2.axhline(100)
BundleFc_Outcome['ROAS'].plot(kind = 'bar',color = 'red',width = 0.4, ax = ax2,position = 0.25)
plt.grid()
#ax2.set_ylim(0, 4000)
ax2.set_ylim(0,300)
plt.title('ROAS & SPEND By Bundle FC',color = 'w',size= 20)
plt.legend([ax2,ax1],labels = ['SPEND','ROAS'],loc = 0)
The code gives me the following picture:
After implementing the suggestion in the comments, the picture looks like this (does not solve the problem):
You can use bbox_to_anchor attribute to set legend location manually.
ax1.legend([ax1],labels = ['SPEND'],loc='upper right', bbox_to_anchor=(1.25,0.70))
plt.legend([ax2,ax1],labels = ['SPEND','ROAS'],loc='upper right', bbox_to_anchor=(1.25,0.70))
https://matplotlib.org/users/legend_guide.html#legend-location
So finally figured it out , was simpler for a some reason
Even managed to add another threshold at level 2 for minimum spend.
fig, ax1 = plt.subplots(figsize = (9,6),sharex=True)
BundleFc_Outcome['Spend'].plot(kind = 'bar',color = 'blue',width = 0.4, ax = ax1,position = 1)
#
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('SPEND', color='b', size = 18)
ax1.set_xlabel('Region',color='w',size = 18)
ax2 = ax1.twinx()
ax2.set_ylabel('ROAS', color='r',size = 18)
ax1.tick_params(axis='x', colors='w',size = 20)
ax2.tick_params(axis = 'y', colors='w',size = 20)
ax1.tick_params(axis = 'y', colors='w',size = 20)
#ax1.text()
#
BundleFc_Outcome['ROAS'].plot(kind = 'bar',color = 'red',width = 0.4, ax = ax2,position = 0.25)
plt.grid()
#ax2.set_ylim(0, 4000)
ax2.set_ylim(0,300)
plt.title('ROAS & SPEND By Region',color = 'w',size= 20)
fig.legend([ax2,ax1],labels = ['SPEND','ROAS'],loc = 0)
plt.hlines([100,20],xmin = 0,xmax = 8,color= ['r','b'])
I don't recommend using the builtin functions of pandas to do more complex plotting. Also when asking a question it is common courtesy to provide a minimal and verifiable example (see here). I took the liberty to simulate your problem.
Due to the change in axes, we need to generate our own legend. First the results:
Which can be achieved with:
import matplotlib.pyplot as plt, pandas as pd, numpy as np
# generate dummy data.
X = np.random.rand(10, 2)
X[:,1] *= 1000
x = np.arange(X.shape[0]) * 2 # xticks
df = pd.DataFrame(X, columns = 'Spend Roast'.split())
# end dummy data
fig, ax1 = plt.subplots(figsize = (9,6),sharex=True)
ax2 = ax1.twinx()
# tmp axes
axes = [ax1, ax2] # setup axes
colors = plt.cm.tab20(x)
width = .5 # bar width
# generate dummy legend
elements = []
# plot data
for idx, col in enumerate(df.columns):
tax = axes[idx]
tax.bar(x + idx * width, df[col], label = col, width = width, color = colors[idx])
element = tax.Line2D([0], [0], color = colors[idx], label = col) # setup dummy label
elements.append(element)
# desired hline
tax.axhline(200, color = 'red')
tax.set(xlabel = 'Bundle FC', ylabel = 'ROAST')
axes[0].set_ylabel('SPEND')
tax.legend(handles = elements)

How to add subfigures in a loop

I have a loop in which I would like to create three subfigures. Here is some code with the function definitions removed.
n = 14
dets = []
entropies = []
N = 1000
fig = plt.figure()
# The loop.
for h in xrange(2,8,2):
for i in xrange(N):
A = (np.random.randint(2, size=(h,n)))*2-1
detA_Atranspose = np.linalg.det(np.dot(A, A.transpose()))
logdetA_Atranspose = math.log(detA_Atranspose + 1,2)
H = compute_entropy(A)
entropies.append(H)
dets.append(logdetA_Atranspose)
ax1 = fig.add_subplot(311)
ax1.plot(dets, entropies, 'ro')
plt.show()
However, there is something I don't know how to do.
In the code above, I need ax2 = fig.add_subplot(312)
ax2.plot(dets, entropies, 'ro') in the second iteration and ax3 = fig.add_subplot(313)
ax3.plot(dets, entropies, 'ro') in the third to create the three subfigures. How should I do that?
You can make use of plt.subplots and do something like:
fig, ax = plt.subplots(nrows = 3, ncols = 1)
hs = [2,8,2]
for p in xrange(3):
h = hs[p]
for i in xrange(N):
# skip other code
ax[p].plot(dets, entropies, 'ro')

If function for annotating from pandas

I'm scatter plotting values from pandas dataframe. I would like to annotate points only if the value is greater than 100. I have no idea how to go about it.
Here's the code I'm working with (it's terrible but I'm very new to this):
female_data = r'/home/jg/Desktop/hurricanedata_f.csv'
female_df = read_csv(female_data)
male_data = r'/home/jg/Desktop/hurricanedata_m.csv'
male_df = read_csv(male_data)
x = female_df['Year']
y = female_df['alldeaths']
z = female_df['Name']
y_mean = [np.mean(y) for i in x]
a = male_df['Year']
b = male_df['alldeaths']
b_mean = [np.mean(b) for i in b]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.annotate('Agnes', xy=(1972,117))
ax1 = fig.add_subplot(1,1,1)
ax1.scatter(x,y, label = 'female', color = 'r')
ax2 = fig.add_subplot(1,1,1)
ax2.scatter(a,b, label = 'male')
ax3 = fig.add_subplot(1,1,1)
ax3.plot(x, y_mean, linestyle='--', color = 'r')
ax4 = fig.add_subplot(1,1,1)
ax4.plot(a, b_mean, linestyle='--', color = 'blue')
plt.title('Hurricanes')
plt.xlabel('Year')
plt.ylabel('Deaths')
plt.legend(loc='upper right')
plt.ylim([-5,300])
plt.xlim([1948,2020])
plt.show()
You can loop over all your data points and check if each is greater than 100. Then give those points an annotation.
import matplotlib.pyplot as plt
import numpy as np
import string
# Fake data
x = np.arange(10)
y = 10*np.random.rand(10) + 95
names = string.lowercase[:10] # first 10 lowercase letters
# Plot data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x,y)
# Annonate points with y values greater than 100
for xi, yi, iname in zip(x,y,names): # Loop over x and y values
if yi > 100: # Check if y is greater than 100
ax.annotate(iname, (xi, yi),size = 30) # Add an annoatation.
plt.show()

Categories