Plotting each country as a seperate line - dataframe

I have a csv file from https://ourworldindata.org/nuclear-weapons-risk and i'm trying to plot an animated plot that shows each country as a separate line but I'm unsure as to how I would do that, this is the code I have so far and it plots the entire end column of stockpile data as one line so each time one country is finished going from 1945 to 2022, it snaps back to 1945 and plots for the next country.
`
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
from itertools import count
import pandas as pd
df=pd.read_csv(r"B:\pythonProject\nuclear-warhead-stockpiles.csv")
x= []
y= []
Entity= []
fig,ax=plt.subplots()
ax.plot(x,y)
counter=count(0,1)
def update(i):
idx=next(counter)
x.append(df.iloc[idx,2])
y.append(df.iloc[idx,3])
plt.cla()
plt.plot(x,y)
plt.xlabel("Year")
plt.ylabel("Nuclear Weapons Stockpile")
plt.title("The Nuclear stockpile of a group of countries from 1945-2022")
plt.legend()
ani=FuncAnimation(fig=fig,func=update,interval=50)
plt.show()
`

Related

Inputting individual data points from an excel dataset alongside a boxplot in matplotlib

using matplotlib, I have constructed a boxplot for a dataset read from excel. I want to include the individual data points alongside my boxplot. Any advice?
Here is the code I used for my boxplot:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
Fast_G = pd.read_excel(r'C:\Users\Rex Reginald\Excel work\MFGP.xlsx')
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.boxplot((Fast_G.MIA, Fast_G.CTL), vert=True, showmeans=True, meanline=True, patch_artist=True,
labels=('MIA', 'CTL'),
medianprops={'linewidth': 2, 'color': 'purple'},
meanprops={'linewidth': 2, 'color': 'red'})
plt.title('MFGP')
plt.ylabel('MP')
plt.show()

seaborn.swarmplot problem with symlog scale: zero's are not expanded

I have a data set of positive values and zero's that I would like to show on the log scale. To represent zero's I use 'symlog' option, but all zero values are mapped into one point on swarmplot. How to fix it?
import numpy as np
import seaborn as sns
import pandas as pd
import random
import matplotlib.pyplot as plt
n = 100
x = np.concatenate(([0]*n,np.linspace(0,1,n),[5]*n,np.linspace(10,100,n),np.linspace(100,1000,n)),axis=None)
data = pd.DataFrame({'value': x, 'category': random.choices([0,1,2,3], k=len(x))})
f, ax = plt.subplots(figsize=(10, 6))
ax.set_yscale("symlog",linthreshy=1.e-2)
ax.set_ylim(ymax=1000)
sns.swarmplot(x="category", y="value", data=data)
sns.despine(left=True)
link to the resulting plot

Understanding plt.show() in Matplotlib

import numpy as np
import os.path
from skimage.io import imread
from skimage import data_dir
img = imread(os.path.join(data_dir, 'checker_bilevel.png'))
import matplotlib.pyplot as plt
#plt.imshow(img, cmap='Blues')
#plt.show()
imgT = img.T
plt.figure(1)
plt.imshow(imgT,cmap='Greys')
#plt.show()
imgR = img.reshape(20,5)
plt.figure(2)
plt.imshow(imgR,cmap='Blues')
plt.show(1)
I read that plt.figure() will create or assign the image a new ID if not explicitly given one. So here, I have given the two figures, ID 1 & 2 respectively. Now I wish to see only one one of the image.
I tried plt.show(1) epecting ONLY the first image will be displayed but both of them are.
What should I write to get only one?
plt.clf() will clear the figure
import matplotlib.pyplot as plt
plt.plot(range(10), 'r')
plt.clf()
plt.plot(range(12), 'g--')
plt.show()
plt.show will show all the figures created. The argument you forces the figure to be shown in a non-blocking way. If you only want to show a particular figure you can write a wrapper function.
import matplotlib.pyplot as plt
figures = [plt.subplots() for i in range(5)]
def show(figNum, figures):
if plt.fignum_exists(figNum):
fig = [f[0] for f in figures if f[0].number == figNum][0]
fig.show()
else:
print('figure not found')

y axis values not displaying on live candlestick plot with webscraped data

Program pull today's ES future's OHLC from cme website and next function create one day bar live plot. Sometimes the y axis appears with current price values other times it appears with single digit values i.e. 1,2,3,4,5
ax_setylim fix the problem. Neither does using another candlestick plot function.
import bleach
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
import matplotlib.animation as animation
from matplotlib import style
def get_data():
req=requests.get('http://www.cmegroup.com/trading/
equity-index/us- index/e-mini-sandp500.html')
html=req.text
htmlBS=BeautifulSoup(html,'lxml')
Open=(htmlBS.find('td',
id="quotesFuturesProductTable1_ESZ7_open")).contents
Last=(htmlBS.find('td',
id="quotesFuturesProductTable1_ESZ7_last")).contents
High=(htmlBS.find('td',
id="quotesFuturesProductTable1_ESZ7_high")).contents
Low=(htmlBS.find('td',
id="quotesFuturesProductTable1_ESZ7_low")).contents
#use bleach module to clean strong tag from Low
Open=bleach.clean(Open,tags=[],strip=True)
Last=bleach.clean(Last,tags=[],strip=True)
High=bleach.clean(High,tags=[],strip=True)
Low=bleach.clean(Low,tags=[],strip=True)
def clean_ohlc(x):
x=x.replace('[','')
x=x.replace(']','')
return x
Open=clean_ohlc(Open)
High=clean_ohlc(High)
Low=clean_ohlc(Low)
Last=clean_ohlc(Last)
OHLC=[Open,High,Low,Last]
OHLC=[x.strip("'").strip('"') for x in OHLC]
OHLC=[float(x) for x in OHLC]
O=[]
H=[]
L=[]
C=[]
O.append(OHLC[0])
H.append(OHLC[1])
L.append(OHLC[2])
C.append(OHLC[3])
return O,H,L,C
style.use('ggplot')
fig=plt.figure()
ax= fig.add_subplot(111)
def update(dummy):
O,H,L,C= get_data()
ax=plt.gca()
ax.clear()
ax.set_xlim([-.5,.5])
candlestick2_ohlc(ax,O,H,L,C,width=.2,
colorup='g',colordown='r',alpha=1.0)
anime=animation.FuncAnimation(fig,update,interval=25)
plt.show()

how to call axes and add it in a new figure in matplotlib

I want to combine the two figures in t1.py and t2.py. l import the two axis named ax1 int1.py and ax2 in t2.py in the new file t.py. now I set a figure in t.py, l want to add the imported two axes as subplots in the new figure, how can l do it?
I have tried one way to do it, but is not well enough:
this is t1.py file
import matplotlib.pyplot as plt
from t import ax01 as ax1
ax1.plot([2,4,5,6,9])
this is t2.py file
import matplotlib.pyplot as plt
from t import ax02 as ax1
ax1.plot([.2,.4,.5,.6,0.9])
this is t.py file
import matplotlib.pyplot as plt
fig1,(ax01,ax02)=plt.subplots(1,2);
execfile('t1.py')
execfile('t2.py')
plt.show()
however, this will call the execfile function.