How to make bar charts for muultiple groups? - pandas

Have a dataframe of multiple groups of stats of two classes, ex:
player position Points target_class
lebron sf 23 1
Magic pg 22 0
How do I make bar charts of the average points per position(5 of them) but split for each class. So side by side plots in pandas.

Without more information it's hard to know what you are expecting. Using sns.barplot like so should get you close to what I think you want.
import seaborn as sns
import numpy as np
ax = sns.barplot(
data=df,
x="position",
y="Points",
hue="target_class",
estimator=np.mean,
)

Related

Generating a mouse heatmap with X, Y coordinates

I'm trying to use Python to generate a mouse heatmap using a large set of X, Y coordinates. I've imported the CSV using Pandas, here's the first few rows to get an idea of what it looks like:
X Y
0 2537 638
1 2516 637
2 2451 644
3 2317 652
4 2147 658
5 1999 647
I've tried using Matplotlib with not a lot of success, so swapped over to Seaborn to attempt to generate the heatmap that way. For reference, this is what I'm hoping to generate (with a different image in the background):
https://imgur.com/s5qiBsB
This is what my current code looks like:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
df = pd.read_csv(r'C:\Users\Jen\Desktop\mp.csv')
df[["x", "y"]] = pd.DataFrame.to_numpy(df)
matrix = np.zeros((df.x.max()+1, df.y.max()+1))
matrix[df.x, df.y] = df.index
sns.heatmap(matrix, cmap='jet')
plt.show()
With the following as a result:
https://imgur.com/12dMBsk
Obviously, this isn't exactly what I'm going for. First off, my x and y axes are swapped. What do I need to do to make my result look more like the example I provided? How do I create that blob effect around the different points?
More than happy to try anything at this point. This dataset is about 13,000 rows but I anticipate it will be even larger in the future.
(For reference, these were captured using 2 monitors, each at a resolution of 1650x1050, hence the large x values)

How can i plotting two columns with string as value in a DataSet with Matplotlib?

I have the following Dataset and I wanna create a plot, which to columns compares with each other.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
ds=pd.read_csv('h-t-t-p-:bit.ly/uforeports') #My DataSet
ds.head(5) # Only the fist 5 rows to show
ds1= ds.head(4).drop(['Colors Reported','State'],axis=1) # Droping of unnecesssary rows
print(ds1)
Now I wanna compare "City" and "Shape Reported" with help of plotting. I found something with Pandas but this is not so elegant!
x=ds.loc[0:100,['State']]
y=ds.loc[0:100,['Shape Reported']]
x.apply(pd.value_counts).plot(kind='bar', subplots=True)
y.apply(pd.value_counts).plot(kind='bar', subplots=True)
Do you know a better solution with Matplotlib to this problem?
This is what I want
It's not exactly clear how you want to compare them.
The simplest way of drawing a bar chart is:
df['State'].value_counts().plot.bar()
df['Shape Reported'].value_counts().plot.bar()
If you just want to do it for the first 100 rows as in your example, just add head(100):
df['State'].head(100).value_counts().plot.bar()
df['Shape Reported'].head(100).value_counts().plot.bar()
EDIT:
To compare the two values you can plot a bivariate distribution plot. This is easily done with seaborn:
import seaborn
sns.displot(df,x='State', y='Shape Reported', height=6, aspect=1.33)
Result:

Extra lane in heat map (pandas)

Here is my file
I plot heat map from it using the following code:
import pandas as pd
import matplotlib.pyplot as plt
new = pd.read_csv(r'path_to_file')
full_list=new.columns.values
new = new[full_list[1:]]
plt.pcolor(new, cmap='Blues')
plt.show()
File has only 11 rows of values, but for some reason 12 rows show up. Do you know what is wrong?
Here is how output looks for me:
There is nothing wrong. First, this has nothing to do with pandas, so we can leave that out and consider the following example
import matplotlib.pyplot as plt
import numpy as np
a = np.random.randint(0,10,size=(11, 2))
plt.pcolor(a, cmap='Blues')
plt.show()
We create an array with 11 rows and 2 columns and plot it. It also shows a 12th row.
The easiest solution is probably to just limit the axis to the number of rows
plt.ylim([0,a.shape[0]])
in this case plt.ylim([0,11]).
However we want to know more...
Is eleven special? Maybe, so let's find out by putting some other numbers in.
1 to 10 work fine. 11 won't. 12 will, 13 not.
So what is special about those numbers, is that matplotlib cannot easily find good axes tickmarks if it is asked to plot 11, 13, ... entities.
This is decided by the matplotlib locator.
The tricky part would now be to find a good locator for 11 entities. I think there is none, as
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 11) )
wont work here. But this may also be a different question now.

Cutting up the x-axis to produce multiple graphs with seaborn?

The following code when graphed looks really messy at the moment. The reason is I have too many values for 'fare'. 'Fare' ranges from [0-500] with most of the values within the first 100.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset("titanic")
y =titanic.groupby([titanic.fare//1,'sex']).survived.mean().reset_index()
sns.set(style="whitegrid")
g = sns.factorplot(x='fare', y= 'survived', col = 'sex', kind ='bar' ,data= y,
size=4, aspect =2.5 , palette="muted")
g.despine(left=True)
g.set_ylabels("Survival Probability")
g.set_xlabels('Fare')
plt.show()
I would like to try slicing up the 'fare' of the plots into subsets but would like to see all the graphs at the same time on one screen. I was wondering it this is possible without having to resort to groupby.
I will have to play around with the values of 'fare' to see what I would want each graph to represent, but for a sample let's use break up the graph into these 'fare' values.
[0-18]
[18-35]
[35-70]
[70-300]
[300-500]
So the total would be 10 graphs on one page, because of the juxtaposition with the opposite sex.
Is it possible with Seaborn? Do I need to do a lot of configuring with matplotlib? Thanks.
Actually I wrote a little blog post about this a while ago. If you are plotting histograms you can use the by keyword:
import matplotlib.pyplot as plt
import seaborn.apionly as sns
sns.set() #rescue matplotlib's styles from the early '90s
data = sns.load_dataset('titanic')
data.hist(by='class', column = 'fare')
plt.show()
Otherwise if you're just plotting value-counts, you have to roll your own grid:
def categorical_hist(self,column,by,layout=None,legend=None,**params):
from math import sqrt, ceil
if layout==None:
s = ceil(sqrt(self[column].unique().size))
layout = (s,s)
return self.groupby(by)[column]\
.value_counts()\
.sort_index()\
.unstack()\
.plot.bar(subplots=True,layout=layout,legend=None,**params)
categorical_hist(data, by='class', column='embark_town')
Edit If you want survival rate by fare range, you could do something like this
data.groupby(pd.cut(data.fare,10)).apply(lambda x.survived.sum(): x./len(x))

Seaborn FacetGrid plots are empty if any of the sub-plots have no data

I have a dataset that I want to plot with FacetGrids using the seaborn library. The problem is my data is "sparse"; some of the individual subplots don't exist (ie. there are zero data points). I would like those cells to either not show up, or just show up and be blank, but still see the subplots that have data. Here's a simple example:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(columns=['a','b','c','d'],
data=[[1,1,1,4],[1,2,2,8],[2,1,2,12],[2,1,3,14]])
print df
g = sns.FacetGrid(df, col='a', row='b', hue='c')
g.map(plt.scatter, 'c', 'd', marker='o')
Unfortunately, when I plot this, I just get four empty plots instead of 3 filled plots and one empty one. If I change the last row of data to [2,2,3,14] instead, then all four plots appear as expected. Is this a bug in seaborn? Can I work around it somehow?