Jupyter widgets clear_output() does not work - python

I was using the ipywidgets dropdown to create plots for the columns listed in the dropdown. I have two issues. Would any one help?
I used the clear_ouput() to clear out the graph before the next selection. But it did not work;
When I first time clicked the first item in the dropdown list ("quarter"), it did not response (No graph showed). I have to select other items first before I can generate the graph for "quarter".
Thanks a lot!
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import ipywidgets as ipw
url = "https://data.london.gov.uk/download/number-international-visitors-london/b1e0f953-4c8a-4b45-95f5-e0d143d5641e/international-visitors-london-raw.csv"
df_london = pd.read_csv(url)
dropdown_Col = ipw.Dropdown(options = ['quarter', 'market', 'dur_stay', 'mode'], description='Sel Col NM:')
output = ipw.Output()
def Col_Sel(ColNm):
output.clear_output()
with output:
sns.set_style("whitegrid")
sns.relplot(x=ColNm, y='visits', data=df_london, kind='line', ci=None)
def dropdown_Col_eventhandler(change):
Col_Sel(change.new)
dropdown_Col.observe(dropdown_Col_eventhandler, names='value')
display(dropdown_Col)
display(output)

I added plt.show() and now The clear_output works.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import ipywidgets as ipw
url = "https://data.london.gov.uk/download/number-international-visitors-london/b1e0f953-4c8a-4b45-95f5-e0d143d5641e/international-visitors-london-raw.csv"
df_london = pd.read_csv(url)
dropdown_Col = ipw.Dropdown(options = ['quarter', 'market', 'dur_stay', 'mode'], description='Sel Col NM:')
output = ipw.Output()
def Col_Sel(ColNm):
output.clear_output()
with output:
sns.set_style("whitegrid")
sns.relplot(x=ColNm, y='visits', data=df_london, kind='line', ci=None)
def dropdown_Col_eventhandler(change):
Col_Sel(change.new)
dropdown_Col.observe(dropdown_Col_eventhandler, names='value')
display(dropdown_Col)
display(output)

Related

Overlay a line plot around diffrent region in Seaborn or Matplotlib

I would like to plot a line plot and make different overlay based on condition as illustrated below.
May I know how, or if possible, please kindly redirect me to right material on achieving the intended objective.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
rng = np.random.default_rng(2)
mlist=[]
for _ in range(4):
m=np.random.rand(4).tolist()
n=rng.integers(0, 6, size=(1)).tolist()*4
df = pd.DataFrame(zip(m,n), columns=['yval','type'])
mlist.append(df)
df=pd.concat(mlist).reset_index(drop=True).reset_index()
sns.lineplot(data=df, x="index", y="yval")
plt.show()
Suggestion using Matplotlib or Seaborn, or any other package are welcome
The filling of the section was achieved using axvspan. I also used text for annotations.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
rng = np.random.default_rng(2)
mlist=[]
for _ in range(4):
m=np.random.rand(4).tolist()
n=rng.integers(0, 6, size=(1)).tolist()*4
df = pd.DataFrame(zip(m,n), columns=['yval','type'])
mlist.append(df)
df=pd.concat(mlist).reset_index(drop=True).reset_index()
g = sns.lineplot(data=df, x="index", y="yval")
overlay = {0:'m',1:'gray',5:'r'}
for i in np.arange(0,len(df),4):
tmp = df.iloc[i:i+4, :]
v = overlay.get(tmp.type.unique()[0])
g.axvspan(min(tmp.index), max(tmp.index)+1, color=v, alpha=0.3)
g.text(((min(tmp.index)+max(tmp.index)+1) / 2)-1, 0.1,'type {}'.format(tmp.type.unique()[0]), fontsize=12)
plt.show()
Using Matplotlib add_patch and text
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as mcolors
# nn=mcolors.CSS4_COLORS
all_colors=list(mcolors.TABLEAU_COLORS.keys())
b=1
np.random.seed(0)
rng = np.random.default_rng(2)
mlist=[]
for _ in range(4):
m=np.random.rand(4).tolist()
n=rng.integers(0, 6, size=(1)).tolist()*4
df = pd.DataFrame(zip(m,n), columns=['yval','type'])
mlist.append(df)
df=pd.concat(mlist).reset_index(drop=True).reset_index()
# df.to_feather('test.feather')
# df=pd.read_feather('test.feather')
df['C'] = df['type'].diff()
df['C']=df['C'].fillna(10)
nb=df.type[(df['C'] != 0)].to_frame().reset_index()
unique_val=nb['type'].drop_duplicates().sort_values().tolist()
ngroup_type=dict(zip(unique_val,[f'type {idx}' for idx in unique_val]))
nb['ngroup']=nb["type"].map(ngroup_type)
color_group=all_colors[:len(unique_val)]
res = dict(zip(unique_val, color_group))
nb["color"] = nb["type"].map(res)
starting_point=nb["index"].values.tolist()
mcolor=nb["color"].values.tolist()
group_type=nb["ngroup"].values.tolist()
nspace=4
nheight=1
fg=sns.lineplot(data=df, x="index", y="yval")
for ncolor,spoint,gtype in zip(mcolor,starting_point,group_type):
fg.axes.add_patch(patches.Rectangle((spoint, 0),
nspace,nheight,edgecolor = 'blue',
facecolor = ncolor,fill=True,alpha=0.1,ls=':') )
fg.axes.text(spoint+1.5, 0.1, gtype , size=10,
va="baseline", ha="left", multialignment="left")
plt.show()

Unable to change color of plotted lines on matplotlib

Referred to this SO post here: Matplotlib set_color_cycle versus set_prop_cycle
But I was unable to set all 20 lines' colors to be different, picture of the graph here:
Here is my code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from cycler import cycler
df = pd.read_csv(r'data.csv', index_col="Date", parse_dates=True)
df.rolling(window=30).max()[30:].head(20)
ax = df.plot()
ax.set(title='Qingdao Port', ylabel='Monthly Average Prices')
ax.set_prop_cycle('color',plt.cm.jet(np.linspace(0,1,20)))
plt.show()
Do help me out here!
User DavidG has helped me with the issue, for future reference the updated code will be included here:
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from cycler import cycler
fig, ax = plt.subplots()
ax.set_prop_cycle('color',plt.cm.tab20(np.linspace(0,1,20)))
df = pd.read_csv(r'data.csv', index_col="Date", parse_dates=True)
df.rolling(window=30).max()[30:].head(20)
df.plot(ax=ax)
ax.set(title='Qingdao Port', ylabel='Monthly Average Prices')
plt.show()

Axis not displaying in Matplotlib

import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-
data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
df = pd.read_csv("FuelConsumption.csv")
df.head()
df1 = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
df1.head(9)
plt.scatter(df1.ENGINESIZE , df1.CO2EMISSIONS , color = "black")
plt.xlabel=("enginesize")
plt.ylabel=("emission")
plt.show()
when i try to run this code i get scatter graph without axis label.
how can i get axis label if anyone can assist me ?
You need to pass the label names to xlabel and ylabel.
If it's throwing error - TypeError: 'str' object is not callable then restart the ipython kernel
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
df = pd.read_csv("FuelConsumption.csv")
df.head()
df1 = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
df1.head(9)
plt.scatter(df1.ENGINESIZE , df1.CO2EMISSIONS , color = "black")
plt.xlabel("enginesize")
plt.ylabel("emission")
plt.show()

Seaborn - Display Last Value / Label

I would like create an plot with to display the last value on line. But i can not create the plot with the last value on chart. Do you have an idea for to resolve my problem, thanks you !
Input :
DataFrame
Plot
Output :
Cross = Last Value In columns
Output Final
# import eikon as ek
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import os
import seaborn as sns; sns.set()
import pylab
from scipy import *
from pylab import *
fichier = "P:/GESTION_RPSE/GES - Gestion Epargne Salariale/Dvp Python/Florian/Absolute
Performance/PLOT.csv"
df = pd.read_csv(fichier)
df = df.drop(columns=['Unnamed: 0'])
# sns.set()
plt.figure(figsize=(16, 10))
df = df.melt('Date', var_name='Company', value_name='Value')
#palette = sns.color_palette("husl",12)
ax = sns.lineplot(x="Date", y="Value", hue='Company', data=df).set_title("LaLaLa")
plt.show()
Do you just want to put an 'X' at the end of your lines?
If so, you could pass markerevery=[-1] to the call to lineplot(). However there are a few caveats:
You have to use style= instead of hue= otherwise, there are no markers drawn
Filled markers work better than unfilled markers (like "x"). You can just use markers=True to use the default markers, or pass a list markers=['s','d','o',etc...]
code:
fmri = sns.load_dataset("fmri")
fig, ax = plt.subplots()
ax = sns.lineplot(x="timepoint", y="signal",
style="event", data=fmri, ci=None, markers=True, markevery=[-1], markersize=10)

How to format y-axis to show percentage with Python Jupyter Notebook lmplot? [duplicate]

I have the following pandas plot:
Is it possible to add '%' sign on the y axis not as a label but on the number. Such as it would show instead of 0.0 it would be 0.0% and so on for all the numbers?
Code:
import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
end = datetime.date.today()
start = datetime.date(2020,1,1)
data = web.DataReader('fb', 'yahoo', start, end)
data['percent'] = data['Close'].pct_change()
data['percent'].plot()
Here is how you can use matplotlib.ticker:
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.show()
Output:
You can now control the display format of the y-axis. I think it will be 0.0%.
yvals = ax.get_yticks()
ax.set_yticklabels(["{:,.1%}".format(y) for y in yvals], fontsize=12)
You can also use plt.gca() instead of using ax
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1.0))

Categories

Resources