How do I change the index of x axis [duplicate] - python

This question already has answers here:
How to plot multiple pandas columns
(3 answers)
Use index in pandas to plot data
(6 answers)
Closed 1 year ago.
I am trying to make an area plot. However the x axis of the graph shows 1,2,3 rather than the year. How can I change this? I saw some related questions here, however the code there is a bit too complicated for me.
My code is:
import matplotlib as mpl
import matplotlib.pyplot as plt
areaplot=r'data.xlsx'
df_areaplot = pd.read_excel(areaplot)
df_areaplot.plot(kind='area')
plt.title('SDG Spending Trend')
plt.ylabel('Amount Spent')
plt.xlabel('Years')
plt.show()

As #tmdavison points out in the comment, you can use column names to determine axes, even with specified lists of columns, i.e.:
df_areaplot.plot(kind='area',
x='BDG',
y=['Citizen Initiatives',
'Education and Employability',
'Enviromental Sustainability',
'Woman Empowerment'])

Related

Python line plotting 2 columns in same DataFrame using Index and count [duplicate]

This question already has answers here:
How to plot multiple pandas columns
(3 answers)
Plot multiple columns of pandas DataFrame using Seaborn
(2 answers)
How do I create a multiline plot using seaborn?
(3 answers)
Closed 26 days ago.
Newbie to Python so am unsure whether this can be done in one graph or not. I have one DataFrame containing Year, Number of Accidents and Number of Fatalities:
I am trying to generate a line plot that shows x axis = Year, y axis = number of instances per year, and 2 lines showing number of each individual column. Using Seaborn, I can only see a way to map 2 columns and hue. Can anyone please provide any advice on whether this is achievable in either Matplotlib or Seaborn.
Tried using Seaborn but cannot work out how to set up x and y axis as required and show 2 individual columns within that:
sns.lineplot(x=f1_safety['NumberOfFatalities'],y=f1_safety['NumberOfAccidents'].count(), hue = f1_safety['year'].count())
plt.show()
There are at least two ways to accomplish what you want to do here.
The simpler one uses pandas built-in plotting API. You can plot dataframes directly when they are already in the correct form. In your case, you need to set the year as the index, and then can plot right away:f1_safety.set_index("year").plot()
If you want to use seaborn, you first need to transform the data into the correct format. seaborn takes x and y, and you can not specify different y columns directly (like y1, y2 and so on). Instead, you need to transform the data into "long format". In such a table, you get one index or id column, one value column and a "description" kind of columns. This works like this:
f1_safety = pd.melt(df, id_vars="year", value_vars=["NumberOfAccidents", "NumberOfFatalities"])
sns.lineplot(data=f1_safety, x="year", y="value", hue="variable")
The plot in both cases looks quite the same:
There are other ways. In particular, in Jupyter you can execute two plot statements in the same cell, and matplotlib will put the plots into the same figure, even cycling through the colors as necessary.

Fill a plot with color from a y upwards to infinity [duplicate]

This question already has answers here:
How to use matplotlib fill_between for default ylim
(1 answer)
How to highlight specific x-value ranges
(2 answers)
Closed 2 months ago.
I am trying to indicate a "dangerous" zone in my sns boxplot.
So far this is what i came up with:
plt.fill_between([0, 6], [danger, danger], danger * 1.2, color='salmon', alpha=0.5)
But since I use sns boxplot, the x values are totally messed up and i had to play with it to get the following result:
I cant really increase the polygon size as the plot grows with it (understandingly).
Ideally i would have wanted to simply paint everything above this threshold as red like so:

Displaying KDE plots in a grid format using Seaborn [duplicate]

This question already has answers here:
How to make seperate Seaborn kdeplots for all different columns from the same pandas Dataframe?
(2 answers)
How to Plot a Matrix of Seaborn Distplots for All Columns in the Dataframe
(3 answers)
Plot multiple columns of pandas DataFrame using Seaborn
(2 answers)
Closed 10 months ago.
I am using the Wisconsin Breast Cancer dataset for a class project and I am attempting to display 10 KDE plots in 5 x 2 layout. Unfortunately,the plots are displayed in scrollable window which is definitely not what I would like.
features = ['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean', 'concave_points_mean', 'symmetry_mean', fractal_dimension_mean']
for feature in features:
df[feature].plot.kde(title=feature)
plt.show()
Any help would be appreciated.
Thank you.

How do I set column colors in a bar plot of a dataframe? [duplicate]

This question already has answers here:
Pandas bar plot -- specify bar color by column
(2 answers)
vary the color of each bar in bargraph using particular value
(3 answers)
Closed 2 years ago.
I was trying the tutorial posted on http://queirozf.com/entries/pandas-dataframe-plot-examples-with-matplotlib-pyplot
and was wondering whether it was possible to have a bar chart created that could have colored columns.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'name':['john','mary','peter','jeff','bill','lisa','jose'],
'age':[23,78,22,19,45,33,20],
'gender':['M','F','M','M','M','F','M'],
'state':['california','dc','california','dc','california','texas','texas'],
'num_children':[2,0,0,3,2,1,4],
'num_pets':[5,1,0,5,2,2,3]
})
df.plot(kind='bar',x='name',y='age')
the current code above creates
.
However, I would like to have the eventual output showing that the columns have a different
.
(The column showing John would be red, Mary would be orange and so on)
Any and all help is appreciated! Thank you.
Specify the colors:
df.plot(kind='bar',x='name',y='age',
color=["red","blue","green","yellow","black","grey","purple"])
to get
You might want to remove the the legend using
df.plot(kind='bar',x='name',y='age',
color=["red","blue","green","yellow","black","grey","purple"],
legend=False)
as it only displays one color.

Asymmetrical errorbar with pandas [duplicate]

This question already has an answer here:
Why is pandas applying the same values on both sides of an asymmetric error bar?
(1 answer)
Closed 5 years ago.
I want to plot asymmetrical errorbars with pandas. According to official docs this should work
df = pd.DataFrame([[1,0.2,0.7]])
fig, ax = plt.subplots()
df[0].plot.bar(yerr=[df[1], df[2]], ax=ax)
But pandas renders errorbar as df[1] for both lower and upper limits (-0.2/+0.2 istead of -0.2/+0.7):
Where do I make a mistake?
I use pandas v0.20.3 with python v2.7.13 under Windows 7.
Your yerr is 1D:
yerr=[df[1], df[2]]
It needs to be 2D, specifically one row per data point and each row having two values for negative and positive error:
yerr=[[df[1], df[2]]]

Categories

Resources