How to pick a new color for each plotted line in matplotlib? [duplicate] - matplotlib

This question already has answers here:
How to pick a new color for each plotted line within a figure in matplotlib?
(7 answers)
Closed 7 months ago.
I have a small problem with the colors when I make a loop for to create my lines
Can you help me please?
I would like to change the color of each line
data = {'Note':['3','3','3','4','4','4','5','5','5','1','2','2','1'],
'Score':['10','10.1','17','17.5','16.5','14.3','10','10.1','17','17.5','16.5','16.5','16.5']}
Create DataFrame
df = pd.DataFrame(data)
Create Plot by loop for
groups=df.groupby("Note")["Score"].min()
for color in ['r', 'b', 'g', 'k', 'm']:
for i in groups.values:
plt.axhline(y=i, color=color)
plt.show()

The reason you are not seeing the colors is because you are running 2 for loops and there are several values which are the same number (like 16.5 and 10). So, the lines get written one on top of the other. You can see the different colors by changing you code like this. But do note that only the last color for a particular y value will be seen.
data = {'Note':['3','3','3','4','4','4','5','5','5','1','2','2','1'],
'Score':['10','10.1','17','17.5','16.5','14.3','10','10.1','17','17.5','16.5','16.5','16.5']}
df = pd.DataFrame(data)
groups=df.groupby("Note")["Score"].min()
print(group.values)
color = ['r', 'b', 'g', 'k', 'm']
j=0
for i in groups.values:
plt.axhline(y=i, color=color[j%5])
j=j+1
plt.show()
OUTPUT

Related

How can I change my yticks in matplotlib? I Want to be like "0, 5, 10..." (currently getting a "0.5, 1.0..." [duplicate]

This question already has answers here:
set y-axis in millions [duplicate]
(3 answers)
How do I make the numbers on the y-axis show values in millions instead of in scientific notation in matplotlib?
(1 answer)
Closed 3 months ago.
enter image description here
import matplotlib.pyplot as plt
cidades = [city for city, df in mv_cidade.groupby('Loja')]
plt.bar(mv_cidade['Loja'], mv_cidade['Faturamento'])
plt.ylabel('Faturamento em milhões')
plt.xlabel('Loja (por Estado)')
plt.xticks(cidades, rotation= 'vertical', size= 9)
plt.show()
It's kinda simple. I just wanna know how to change the yticks (0.5, 1.0, 1.5) to something like (5, 10, 15, 20)
Can anyone help?
I've already tried to put the "original" values
plt.yticks([6480300, 6868600, 7060500, 7303000, 7441800, 13111300, 14087900, 14867800, 22098300])
that was the result

Making multiple pie charts out of a pandas dataframe (one for each column)

My question is similar to Making multiple pie charts out of a pandas dataframe (one for each row).
However, instead of each row, I am looking for each column in my case.
I can make pie chart for each column, however, as I have 12 columns the pie charts are too much close to each other.
I have used this code:
fig, axes = plt.subplots(4, 3, figsize=(10, 6))
for i, (idx, row) in enumerate(df.iterrows()):
ax = axes[i // 3, i % 3]
row = row[row.gt(row.sum() * .01)]
ax.pie(row, labels=row.index, startangle=30)
ax.set_title(idx)
fig.subplots_adjust(wspace=.2)
and I have the following result
But I want is on the other side. I need to have 12 pie charts (becuase I have 12 columns) and each pie chart should have 4 sections (which are leg, car, walk, and bike)
and if I write this code
fig, axes = plt.subplots(4,3)
for i, col in enumerate(df.columns):
ax = axes[i // 3, i % 3]
plt.plot(df[col])
then I have the following results:
and if I use :
plot = df.plot.pie(subplots=True, figsize=(17, 8),labels=['pt','car','walk','bike'])
then I have the following results:
Which is quite what I am looking for. but it is not possible to read the pie charts. if it can produce in more clear output, then it is better.
As in your linked post I would use matplotlib.pyplot for this. The accepted answer uses plt.subplots(2, 3) and I would suggest doing the same for creating two rows with each 3 plots in them.
Like this:
fig, axes = plt.subplots(2,3)
for i, col in enumerate(df.columns):
ax = axes[i // 3, i % 3]
ax.plot(df[col])
Finally, I understood that if I swap rows and columns
df_sw = df.T
Then I can use the code in the examples:
Making multiple pie charts out of a pandas dataframe (one for each row)

Generate legend with matplotlib based on the values in column [duplicate]

This question already has answers here:
Scatter plots in Pandas/Pyplot: How to plot by category [duplicate]
(8 answers)
Closed 3 years ago.
Assume we have a dataframe of 4 individuals' scores in 2 different tests and the 3rd column tells us if they passed or failed overall
df:
[10,20,failed
10,40,passed
20,40,passed
30,10,failed]
I would like to generate a scatter plot with the scores of the 1st column on the x axis, the scores of the 2nd test on the y axis, and indicate with color (or marker) if they passed or failed. I have achieved this with:
plt.scatter(x=df[column1], y=df[column2], c=df[column3])
The question is, how can I have a legend based on the color (or marker) and column3?
[red: failed
blue: passed]
Here's my suggestion: Plot the failed an passed separately to get their handles, which can then be used for the legend.
fig = plt.figure()
ax1 = fig.add_subplot(111)
passed = ax1.scatter(x=df.loc[df[column3].eq('passed'), column1], y=df.loc[df[column3].eq('passed'), column2], c='green')
failed = ax1.scatter(x=df.loc[df[column3].eq('failed'), column1], y=df.loc[df[column3].eq('failed'), column2], c='red')
ax1.legend(handles=[passed, failed], labels=['Passed', 'Failed'])

bars not proportional to value - matplotlib bar chart [duplicate]

This question already has an answer here:
Difference in plotting with different matplotlib versions
(1 answer)
Closed 4 years ago.
I am new to matplotlib and am trying to plot a bar chart using pyplot. Instead of getting a plot where the height of bar represents the value, I am getting bars that are linearly increasing in height while their values are displayed on the y-axis as labels.
payment_modes = ['Q', 'NO', 'A', 'C', 'P', 'E', 'D']
l1=[]
l2=[]
for i in payment_modes:
l.append(str(len(df[df['PMODE_FEB18']==i])))
# here l = ['33906', '37997', '815', '4350', '893', '98', '6']
plt.figure()
plt.bar(range(7),l)
This is what I am getting:
The problem is that you seem to be feeding bar with strings, not with numerical quantities. If you instead use the actual numerical quantities, bar will behave as you would expect:
import matplotlib.pyplot as plt
l = [33906, 37997, 815, 4350, 893, 98, 6]
plt.figure()
plt.bar(range(7),l)
plt.show()
gives

How can I change the filled color of stacked area plot in DataFrame?

I want to change the filled color in the stacked area plots drawn with Pandas.Dataframe.
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot.area(linewidth=0);
The area plot example
Now I guess that the instance return by the plot function offers the access to modifying the attributes like colors.
But the axes classes are too complicated to learn fast. And I failed to find similar questions in the Stack Overflow.
So can any master do me a favor?
Use 'colormap' (See the document for more details):
ax = df.plot.area(linewidth=0, colormap="Pastel1")
The trick is using the 'color' parameter:
Soln 1: dict
Simply pass a dict of {column name: color}
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'], )
ax = df.plot.area(color={'b':'0', 'c':'#17A589', 'a':'#9C640C', 'd':'#ECF0F1'})
Soln 2: sequence
Simply pass a sequence of color codes (it will match the order of your columns).
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'], )
ax = df.plot.area(color=('0', '#17A589', '#9C640C', '#ECF0F1'))
No need to set linewidth (it will automatically adjust colors). Also, this wouldn't mess with the legend.
The API of matplotlib is really complex, but here artist Module gives a very plain illustration. For the bar/barh plots, the attributes can be visited and modified by .patches, but for the area plot they need to be with .collections.
To achieve the specific modification, use codes like this.
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot.area(linewidth=0);
for collection in ax.collections:
collection.set_facecolor('#888888')
highlight = 0
ax.collections[highlight].set_facecolor('#aa3333')
Other methods of the collections can be found by run
dir(ax.collections[highlight])