How to change the color of lines within a subplot?

2024/10/4 21:25:08

My goal is to create a time series plot for each column in my data with their corresponding rolling mean. I'd like the color of the lines across subplots to be different. For example, for gym and rolling_mean_gym in the second subplot, the color of the lines should be purple and red. How do I do this?

When I set the color option inside plot(), it changes the color of both the raw data plot and the rolling mean plot, which is not ideal.

I created the plot below by calculating the rolling mean of each column of the time series using the following code:

# calculate rolling mean
def rolling_mean(col):rolling_mean_col = 'rolling_mean_{}'.format(col)df[rolling_mean_col] = df[col].rolling(12).mean()# create rolling mean columns
cols = ['diet', 'gym', 'finance']
for col in cols:rolling_mean(col)# plot data in subplots
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(13,10));
df[['diet', 'rolling_mean_diet']].plot(ax=axes[0]);
df[['gym', 'rolling_mean_gym']].plot(ax=axes[1]);
df[['finance', 'rolling_mean_finance']].plot(ax=axes[2]);

enter image description here

Answer

One option is to provide a list of colors: .plot(..., color=['red', 'blue']).

Pandas plot() method is just a thin wrapper around matplotlib plotting methods. Any non-consumed keyword argument will be passed on to them.

df = pd.DataFrame()
df['diet'] = np.random.random_sample(100)
df['rolling_mean_diet'] = np.random.random_sample(100) / 10 + 0.5df['gym'] = np.random.random_sample(100)
df['rolling_mean_gym'] = np.random.random_sample(100) / 10 + 0.5fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(13,10));
df[['diet', 'rolling_mean_diet']].plot(ax=axes[0], color=['red', 'green']);
df[['gym', 'rolling_mean_gym']].plot(ax=axes[1], color=['purple', 'red']);

multi-colored lines plot

https://en.xdnf.cn/q/70561.html

Related Q&A

Cythons calculations are incorrect

I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:from __future__ import division pi = 0 l = 1 x = True while True:if x:pi…

Python: NLTK and TextBlob in french

Im using NLTK and TextBlob to find nouns and noun phrases in a text:from textblob import TextBlob import nltkblob = TextBlob(text) print(blob.noun_phrases) tokenized = nltk.word_tokenize(text) nouns =…

How can I run a script as part of a Travis CI build?

As part of a Python package I have a script myscript.py at the root of my project and setup(scripts=[myscript.py], ...) in my setup.py.Is there an entry I can provide to my .travis.yml that will run my…

Writing nested schema to BigQuery from Dataflow (Python)

I have a Dataflow job to write to BigQuery. It works well for non-nested schema, however fails for the nested schema.Here is my Dataflow pipeline:pipeline_options = PipelineOptions()p = beam.Pipeline(o…

Python decorators on class members fail when decorator mechanism is a class

When creating decorators for use on class methods, Im having trouble when the decorator mechanism is a class rather than a function/closure. When the class form is used, my decorator doesnt get treated…

Why does comparison of a numpy array with a list consume so much memory?

This bit stung me recently. I solved it by removing all comparisons of numpy arrays with lists from the code. But why does the garbage collector miss to collect it?Run this and watch it eat your memor…

StringIO portability between python2 and python3 when capturing stdout

I have written a python package which I have managed to make fully compatible with both python 2.7 and python 3.4, with one exception that is stumping me so far. The package includes a command line scr…

How to redirect data to a getpass like password input?

Im wring a python script for running some command. Some of those commands require user to input password, I did try to input data in their stdin, but it doesnt work, here is two simple python program…

How to grab one random item from a database in Django/postgreSQL?

So i got the database.objects.all() and database.objects.get(name) but how would i got about getting one random item from the database. Im having trouble trying to figure out how to get it ot select on…

Pyspark Dataframe pivot and groupby count

I am working on a pyspark dataframe which looks like belowid category1 A1 A1 B2 B2 A3 B3 B3 BI want to unstack the category column and count their occurrences. So, the result I want is shown belowid A …