How to remove vertical line from plot? - python

I'm getting a seemingly random vertical line on my plot and I'm unsure how to remove it. Here's the code to create the plot:
import pandas as pd
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
fig = plt.figure()
df=pd.read_csv("Resources/outmerge.csv")
print(df.head())
x='month'
y ='Count'
sns.set_style("dark", {'axes.grid' : False})
ax = sns.lineplot('month', 'Count', data=df, marker='o',markersize=8,markers=True, label='2017')
ax = sns.lineplot('month', 'Count2', data=df, marker='^',markersize=8,markers=True, label='2018')
ax.grid(False)
fname='Resources/output.png'
plt.savefig(fname, dpi=300)
plt.show()
And this is the resulting plot. Note the vertical line at x axis: 1. I'm running seaborn 0.9.0.

Related

countplot and pieplot inverting labels colors

I´m plotting a countplot and a pieplot but "male" and "female" are tagged in opposite colors in each of them
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(1,figsize=(20,5))
sns.countplot(x="sex",data=insurance_ds) #plotting histogram
plt.title("Male/Female Frequency",fontsize=25)
plt.xlabel("Sex",fontsize=20)
plt.ylabel("Frequency",fontsize=20)
plt.tick_params(labelsize=12)
plt.xticks(rotation=90)
plt.yticks(rotation=45)
fig, ax = plt.subplots(1,figsize=(5,5))
insurance_ds["sex"].value_counts().plot.pie(autopct='%1.1f%%',shadow=True,textprops={'fontsize': 10})
plt.title("Male/Female Frequency",fontsize=25)
If you set your column as a category, it should work too:
import matplotlib.pyplot as plt
import seaborn as sns
insurance_ds = pd.DataFrame({'sex':np.random.choice(['male','female'],1000)})
insurance_ds['sex'] = pd.Categorical(insurance_ds['sex'],categories=['male','female'])
fig, ax = plt.subplots(1,2,figsize=(10,5))
sns.countplot(x="sex",data=insurance_ds,ax=ax[0])
insurance_ds["sex"].value_counts().plot.pie(autopct='%1.1f%%',shadow=True,textprops={'fontsize': 10},ax=ax[1])

Why are two figures showing up

I have the following code
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
info = {"Quiz":[1,2,5,4,3,2,6,5,7],
"Score":[1,6,4,2,8,9,10,5,7]}
df = pd.DataFrame.from_dict(info)
fig, ax = plt.subplots(figsize=(6,4))
sns.catplot(x="Quiz", y = 'Score', data=df, ax=ax)
plt.show()
This is what I am seeing.
Why are there two images showing?
Reading the documentation, catplot doesn't return an ax object.

Matplotlib/Seaborn: how to plot a rugplot on the top edge of x-axis?

Suppose I draw a plot using the code below. How to plot the rug part on the top edge of x-axis?
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(np.random.normal(0, 0.1, 100), rug=True, hist=False)
plt.show()
The seaborn.rugplot creates a LineCollection with the length of the lines being defined in axes coordinates. Those are always the same, such that the plot does not change if you invert the axes.
You can create your own LineCollection from the data though. The advantage compared to using bars is that the linewidth is in points and therefore no lines will be lost independend of the data range.
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns
def upper_rugplot(data, height=.05, ax=None, **kwargs):
from matplotlib.collections import LineCollection
ax = ax or plt.gca()
kwargs.setdefault("linewidth", 1)
segs = np.stack((np.c_[data, data],
np.c_[np.ones_like(data), np.ones_like(data)-height]),
axis=-1)
lc = LineCollection(segs, transform=ax.get_xaxis_transform(), **kwargs)
ax.add_collection(lc)
fig, ax = plt.subplots()
data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)
upper_rugplot(data, ax=ax)
plt.show()
Rugs are just thin lines at the data points. Yo can think of them as thin bars. That being said, you can have a following work around: Plot distplot without rugs and then create a twin x-axis and plot a bar chart with thin bars. Following is a working answer:
import numpy as np; np.random.seed(21)
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots()
data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)
ax1 = ax.twinx()
ax1.bar(data, height=ax.get_ylim()[1]/10, width=0.001)
ax1.set_ylim(ax.get_ylim())
ax1.invert_yaxis()
ax1.set_yticks([])
plt.show()

Python pyplot x-axis label rotation

I am trying to rotate the xaxis labels but the xticks function below has no effect and the labels overwrite each other
import matplotlib.pyplot as plt
import seaborn as sns
corrmat = X.corr()
plt.xticks(rotation=90)
plt.figure(figsize=(15,16))
ax = sns.heatmap(corrmat, vmin=0, vmax=1)
ax.xaxis.tick_top()
After using suggested code changes: I get the following but I still want to increase the size of the heatmap
setp looks to be the way to go with pyplot (inspiration from this answer). This works for me:
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np; np.random.seed(0)
data = np.random.rand(10, 12)
ax = sns.heatmap(data)
ax.xaxis.tick_top()
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.show()
Obviously I don't have your data, hence the numpy random data, but otherwise the effect is as required:

How do I change the plot size of a regplot in Seaborn?

Something similar to the fig.set_size_inches(18.5, 10.5) of matplotlib.
You can declare fig, ax pair via plt.subplots() first, then set proper size on that figure, and ask sns.regplot to plot on that ax
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# some artificial data
data = np.random.multivariate_normal([0,0], [[1,-0.5],[-0.5,1]], size=100)
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 10.5)
sns.regplot(data[:,0], data[:,1], ax=ax)
sns.despine()
Or a little bit shorter:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# some artificial data
data = np.random.multivariate_normal([0,0], [[1,-0.5],[-0.5,1]], size=100)
# plot
sns.set_style('ticks')
g = sns.regplot(data[:,0], data[:,1])
g.figure.set_size_inches(18.5, 10.5)
sns.despine()

Categories

Resources