pandas


Change color of legend to match line plot matplotlib pandas


Update, edited code to mcve version problem is in line 17.
I am trying to plot a multiple line chart from a .csv file. I have managed to change the default colors in the plot to tableau20 color scheme. When I generate a legend the colors in the legend remain the default colors. If I try to add a color command to the legend code section I get errors. TypeError: init() got an unexpected keyword argument 'color'. Is there a way to match the legend colors to the colors in the main chart body?
Here is the code and a few lines of the data.
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
df=pd.read_csv('cch30.csv')
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150)]
for i in range(len(tableau20)):
r, g, b = tableau20[i]
tableau20[i] = (r / 255., g / 255., b / 255.)
ax = df.plot(kind='line', x=df.columns[0],y=df.columns[1:8])
species= ['A. bellonorium', 'A. fuscolingua', 'A. mucronata', 'A. depressa', 'A. novazelandia', 'A. spp', 'A. australis']
for rank, column in enumerate(species):
plt.plot(df.Position.values,
df[column.replace("\n", " ")].values,
lw=1, color=tableau20[rank])
lines, labels = ax.get_legend_handles_labels()
#problem in the next line when i try to tell it to use tableau20 by adding color=tableau20[rank]after fontsize
ax.legend(lines[0:8], labels[0:8], loc='best', fontsize=8, color=tableau20[rank])
plt.show()
Position,A. bellonorium,A. fuscolingua,A. mucronata,A. depressa,A. novazelandia,A. spp,A. australis
1,17,9,33,22,15,20,78
2,17,9,33,21,14,22,77
3,17,9,34,20,14,23,78
4,17,9,35,21,12,23,79
5,17,9,34,22,12,24,75
6,17,9,34,22,13,24,75
7,17,9,34,22,13,24,74
8,17,9,34,22,15,24,76
9,16,9,36,20,14,24,76
10,16,9,36,20,15,26,75
11,16,9,37,20,15,27,74
12,16,9,36,21,15,26,74
13,16,9,34,21,15,27,75
14,16,9,34,23,15,27,75
15,16,9,34,24,16,26,75
16,16,9,34,24,16,28,76
17,16,9,33,24,16,28,77
18,15,9,34,24,14,28,77
19,15,9,32,25,14,28,77
20,15,9,32,25,13,28,77
21,15,9,31,25,13,29,79
22,15,9,31,25,13,29,79
23,15,9,32,25,13,29,78
24,15,9,31,25,12,29,79
25,15,9,30,25,12,29,78
26,15,9,30,25,12,28,79
27,15,9,29,24,13,30,80
28,15,9,30,24,13,30,80
29,14,9,29,23,11,30,77
I am not able to run your exact code because I do not have access to the csv that you are using so I'm just guessing as to what your dataframe looks like. But you should be able to adapt the following code to what you need. I tried to make the code as minimum as possible as this will be easier to troubleshoot if you run into issues
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([[1, 1, 1], [.5, 1, 2]], columns=['A. bellonorium', 'A. fuscolingua', 'A. mucronata'])
tableau20 = [(31, 119, 180), (255, 152, 150), (255, 127, 14)]
tableau20 = [(r/255, g/255, b/255) for r, g, b in tableau20]
f, ax = plt.subplots()
for rank, column in enumerate(df.columns):
ax.plot(df.index, df[column], color=tableau20[rank], label=column)
ax.legend(loc='best')
the legend method doesn't have a color parameter which is why you were getting the error, I'm not sure why you weren't getting the correct colors in the labels, however you don't need to explicitly state what the colors are, as those are contained in the axes object. You may also want to define the labels in the plotting method so that they show up in the legend. Good luck]1
This code got the result I wanted at this stage. Thanks to all those who helped
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
df=pd.read_csv('coveragechart.csv')
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150)]
for i in range(len(tableau20)):
r, g, b = tableau20[i]
tableau20[i] = (r / 255., g / 255., b / 255.)
f, ax = plt.subplots()
for rank, column in enumerate(df.columns[1:8]):
ax.plot(df.index, df[column], color=tableau20[rank], label=column)
plt.ylabel('Coverage')
plt.xlabel('Position')
ax.legend(loc='best', fontsize=8)
plt.savefig('cov.png', bbox_inches='tight', dpi=300)
plt.show()

Related Links

appending list of lists to pd.Dataframe()
how to perform where and distinct count operation in pandas dataframe?
Pandas Dataframe - Using index as value when slicing/filtering
How can I select out columns where the first values are NaN?
Record limitation in pandas dataframe when importing from a csv file
count of unique values in pandas dataframe column
Rolling sums on pandas dataframe
Pandas Bug - Error when inserting list serialize as string
Formatting index of a pandas table in a plot
resample over consecutive chunks of large size CSV
Too many possibilities for categorical fields
How to install pandas on virtual machine?
How to change particular column value when defined mask is true?
Pandas/NumPy: concisely label first N values matching a mask
fast way to make index prefix with an alphabet
Is there a way to better format Pandas data frames when printing them in Sublime text?

Categories

HOME
pypi
webpack
omnet++
mfc
google-api-php-client
tinymce
hp-exstream
relayjs
react-router
cvs
microservices
sqlite3
google-project-tango
baqend
slurm
volttron
visual-studio-2005
visual-studio-cordova
zebra-printers
caml
seaborn
pc
normalizr
code-review
ml
facebook-instant-articles
web-sql
wkwebview
qhull
centos6.5
selectedindexchanged
social-media
publish
large-file-upload
quote
procdump
media-queries
phonegap
http-status-code-503
caret
uiswipegesturerecognizer
mozilla
sequential
ios5
http-digest
overlap
scaffold
dynamics-crm-2013
document.write
opshub
lumberjack
mapzen
elmah
node-gyp
angular2-meteor
auto-update
angular-resource
jsch
smartcontracts
upstart
dds
diagnostics
typed-lambda-calculus
python-cryptography
cudafy.net
webdriverjs
specrun
database-optimization
autorest
firebaseui
python-stackless
pickadate
nessus
unity-networking
tmuxinator
kcachegrind
0xdbe
cakephp-3.1
ideamart
javax.mail
gadt
applescript-objc
zend-route
ceil
tld
oam
eclipse-memory-analyzer
qt-faststart
robotics-studio
pvrtc
libstdc++
venn-diagram
newtonscript
hosts-file
dbproviderfactories
work-stealing
mod-auth
heartbeat
table-footer
suppress
routedevent
firefox4
virtual-functions
geneva-server

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App