Need to run cell twice for the changed code to show output - numpy

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

Related

How to create a box plot from a frequency table

In the table below, I have values and frequencies. I'd like to draw a box-plot using Jupyter Notebook. I googled it but not able to find any answers.
My idea is to create a column, 2,2,2,2,4,4,4,4,4,4,4,...
But I think there must be a better way.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
value=np.array([2,4,6,7,10])
freq=np.array([4,7,8,5,2])
# do something here
plt.boxplot(newdata)
plt.show()
use numpy's repeat:
newdata = np.repeat(value,freq)

Axes3D doesn't show plots

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:

Seaborn y labels are overlapping

So I tried to make a categorical plot of my data and this is what my code and the graph.
import pandas as pd
import numpy as np
import matplotlib as plt
import seaborn as sns
sns.set(style="whitegrid")
sns.set_style("ticks")
sns.set_context("paper", font_scale=1, rc={"lines.linewidth": 6})
sns.catplot(y = "Region",x = "Interest by subregion",data = sample)
Image:
How can I make the y-labels more spread out and have a bigger font?
Try using sns.figure(figsize(x,y)) and sns.set_context(context=None,font_scale=1).
Try different values for these parameters to get the best results.

Define hues by column values in seaborn barplot

I would like the colour of the columns to be determined by their value on the x-axis, e.g. bars with identical values on the x-axis should have identical colours assigned to them.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(index=['A','B','C','D','E','F'],data={'col1':np.array([2.3423,4.435,9.234,9.234,2.456,6.435])})
ax = sns.barplot(x='col1', y=df.index.values, data=df,palette='magma')
This is what it looks like at the moment with default settings. I presume there is a simple elegant way of doing this, but interested in any solution.
Here a solution:
import seaborn as sns
import matplotlib as mpl, matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(index=['A','B','C','D','E','F'],
data={'col1':np.array([2.3423,4.435,9.234,9.234,2.456,6.435])})
ax = sns.barplot(x='col1', y=df.index.values, data=df,
palette=mpl.cm.magma(df['col1']*.1))
Note: mpl.cm.magma is a Colormap instance and is used to convert data values (floats) from the interval [0, 1] to colors that the Colormap represents. If you want "auto scaling" of your data values, you could use palette=mpl.cm.ScalarMappable(cmap='magma').to_rgba(df['col1']) instead in the sns.barplot() call.
Here the output:

Use ipywidgets to interatively find best position matplotlib text

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)