I want to visualize world population by year using GeoPandas.
This is the code I am using :
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML
fig,ax=plt.subplots(1,1,figsize=(15,5))
def animation_bar(year):
filtered=merged[merged['Year']==year]
filtered.plot(ax=ax,column='Population_x',legend=True,cmap='Reds')
animator=animation.FuncAnimation(fig,animation_bar,frames=merged['Year'].unique(),interval=1000)
HTML(animator.to_jshtml())
The output looks like this:
How to modify the code for proper result?
Related
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
df = pd.DataFrame({'day':[1,2,3,4,5],'visitors':[200,302,480,590,680],'Bounce_rate':[20,30,40,50,60]})
df.set_index('day',inplace=True)
df.plot()
plt.show()
output is <Figure size 640x480 with 1 Axes>, the desired output is a graph (in VS Code).
I can see my code is correct when using cloud jupyter by achieving the desired output but it's not possible in VS Code jupyter view...
Am I doing something wrong? or is it something else?
I've run into an issue where I need to run the same cell twice after making a change. I've included a gif and the code.
In the gif I first change the seaborn style to darkgrid and run it, this should show the output as changed to the specified style on the first run, but I need to run it twice in order for the output to change.
Here is the code:
%matplotlib inline
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,14,100)
for i in range(1,5):
plt.plot(x,np.sin(x+i*0.5)*(7-i))
sns.set_style("white", {'axes.axisbelow': False})
plt.show()
I have tried separating the import lines to a previous cell but still the problem persists
set your style, before you plot anything . Move the line sns.set_style before for loop. It should work.
%matplotlib inline
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sns.set_style("darkgrid", {'axes.axisbelow': False})
x = np.linspace(0,14,100)
for i in range(1,5):
plt.plot(x,np.sin(x+i*0.5)*(7-i))
plt.show()
I want to get rid of the white border when I save my image to a png in python.
I tried plt.box(on=None), plt.axis('off'). I tried setting the figure's 'frameon' parameter to false.
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
figure(num=None, figsize=(7.965,7.965), dpi=80,facecolor='none',clear=True)
plt.box(on=None)
plt.axis('off')
plt.imshow(Data, cmap='Greys_r', norm=Norm,origin='lower',aspect='auto',interpolation='nearest')
plt.savefig(locationFITSfolder+fitsFile[:-5],transparent=False,bbox=False)
I want there to be no white border to my image. Transparent.
If you change the parameters to the savefig function, you will get the desired output.
Specifically, you must use transparent=True. Note that bbox=False and frameon=False are optional, and only change the width of transparent space around your image.
Adapting from your sample code:
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
#create sample data
import numpy as np
Data = np.random.random([4,4])
figure(num=None, figsize=(7.965,7.965), dpi=80,facecolor='none',clear=True)
plt.box(on=None)
plt.axis('off')
plt.imshow(Data, cmap='Greys_r',origin='lower',aspect='auto',interpolation='nearest')
plt.savefig(locationFITSfolder+fitsFile[:-5],transparent=True)
(sidenote -- you may wish to use os.path.join, .split, and .splitext for file I/O, instead of slicing string names)
This yields the expected image output: (note that the image has transparent borders when you open it in a new tab or download it).
I am practicing Axes3D to play with 3D graph. When I ran code, I am able to produce the axis, but no plots in it.
from mpl_toolkits.mplot3d import Axes3D
df_test=pd.DataFrame(data=np.random.normal(0,1,(20,3)),columns=['a','b','c'])
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.scatter=(df_test['a'],df_test['b'],df_test['c'])
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
plt.show()
Result is like below: As shown, there is no plots, only axis. What did I do wrong in my code? Many thanks!
The line ax.scatter=(df_test['a'],df_test['b'],df_test['c']) should be replaced with
ax.scatter(df_test['a'],df_test['b'],df_test['c']), because you do not need the = operator.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
df_test=pd.DataFrame(data=np.random.normal(0,1,(20,3)),columns=['a','b','c'])
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.scatter(df_test['a'],df_test['b'],df_test['c'])
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
plt.show()
The result is:
I am interested in using the interact function to use a slider to adjust the position of text in a matplotlib plot (you know, instead of adjusting the position, running the code, and repeating 1000 times).
Here's a simple example of a plot
import matplotlib.pyplot as plt
x=0.2
y=0.9
plt.text(x, y,'To move',size=19)
plt.show()
and some interact code
from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
def f(x):
return x
interact(f, cx=0.2)
I'm wondering how I can combine these to generate a plot with the text along with a slider that will interactively move the text based on the specified value for x. Is this possible? What if I want to do the same for y?
Thanks in advance!
Here you go:
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact
def do_plot(x=0.2, y=0.9):
plt.text(x, y,'To move',size=19)
plt.show()
interact(do_plot)