Python - Plot values in different color [duplicate] - python

This question already has answers here:
How to plot one line in different colors
(5 answers)
Closed 6 years ago.
I am new to matplotlib and I need to plot on the same figure a large amount of data. My initial code is
data = np.genfromtxt('Data.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['CSX', 'CSY'])
fig = plt.figure()
myPlot = fig.add_subplot(111)
myPlot.plot(data['CSX'], data['CSY'], color='r', label='the data')
leg = myPlot.legend()
plt.show()
The result is acceptable, I need though to have two different colors on these data, based on a third value. Could you point me to the correct direction? Thanks!

Filter your data into 2 or more sets based on some value/condition and just call plot for each set of data with different colour values.

Related

Undesired shadow in matplotlib pyplot [duplicate]

This question already has answers here:
Convert dataframe index to datetime
(4 answers)
Plot the x-axis as a date
(2 answers)
Plotting dates on the x-axis
(4 answers)
Closed 5 months ago.
I'm trying to plot some data for school project. However an ugly shadow appears when I do so. I have no clue of what it can be.
Here is my code:
index_labels = np.empty(len(smoothed), dtype=object)
for i in range(len(index_labels)):
index_labels[i] = ""
if i%365 == 0:
index_labels[i] = 2015 + int(i//365)
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.set_xticklabels(index_labels)
# plt.legend()
plt.show()
and here is the different variables used so you have an idea:
and a zoom on the plot :
Thanks to all of you! Greetings :)
Solution from #BigBen:
from matplotlib.ticker import MultipleLocator
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(730))
plt.show()
Multiple has a very good name: it only shows the label for the multiple of n.
EDIT: as find later, matplotlib do auto axis labeling for dates. Only problem was that column was recognized as string. pandas.to_datetime allow you to convert it back to pandas datetime type.

how to append a group of number at different index in a list to different list [duplicate]

This question already has answers here:
plot different color for different categorical levels using matplotlib
(8 answers)
Plotting multiple scatter plots pandas
(5 answers)
Closed 6 months ago.
pls, how do I visualize multiple independent variable against a single dependent variable in a single scatter plot in python.
I tried doing it like this :
plt.scatter(df[["Bedroom","Bathroom,"Building_Size","Plot_of_Land"], df["Price"])
But it didn't work
/
relevant_cols = ["Bedroom", "Bathroom", "Building_Size", "Plot_of_Land"]
x_min, x_max = df[relevant_cols].min().min() - 1, df[relevant_cols].max().max() + 1
_, ax = plt.subplots()
for column, colour in zip(relevant_cols, ["tab:orange", "tab:blue", "tab:green", "tab:red"]):
df.plot(x=column, y='price', kind='scatter', ax=ax, color=colour,
label=column, ylabel='', xlim=(x_min, x_max))

Fixing labels of a 6 x 6 graph [duplicate]

This question already has answers here:
Improve subplot size/spacing with many subplots
(8 answers)
Closed 1 year ago.
Hi I'm very new to Python, and I'm trying to fix the labels because they overlap, (as seen in the picture). I figured the hspace and the wspace is the columns, but I'm not sure exactly how to adjust everything else in the labels, I don't want to mess with the x axis. Is there a way to make this plot look clearer?
Here's what I have:
_, axes = plt.subplots(nrows=6, ncols=6, sharex=True)
plt.suptitle('mean activity duration by time of day')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
for ax, (activity, df) in zip(axes.ravel(), df_all.groupby('e')):
(df.groupby('f')
.d
.mean()
.plot(ax=ax,
kind='bar',
title=activity,
xlabel='time'))
6 x 6 bar graph:
Use constrained_layout.
use a larger figure size so your titles are not larger than your axes
use a smaller font size for the titles.
You can use tight_layout if you prefer, but constrained_layout is more flexible.
You can try to use plt.tight_layout, adjusts subplot params so that the subplot(s) fits in to the figure area

Increasing each subplot's size and adjusting their width, matplotlib [duplicate]

This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 3 years ago.
I have a dataset from sci-kit learn, fetch_lfw_people.
import matplotlib.pyplot as plt
# plotting faces
fig, ax = plt.subplots(3,5)
# fig.subplots_adjust(wspace=2)
for enumerate_counter, axi in enumerate(ax.flat):
axi.imshow(faces.images[enumerate_counter], cmap='bone')
axi.set(xticks=[], yticks=[],xlabel=faces.target_names[faces.target[enumerate_counter]])
while trying to show images using subplots and labeling each image with proper name, I want to increase the size of each images and also separate them wide enough so that names do not overlap.
I've tried
fig.subplots_adjust(wspace=2)
however this separates images so that names do not overlap however images gets smaller in size.
Anyway I could resolve this issue?
I will give some examples with some sample numbres that may lead you in the right direction:
plt.figure(figsize=(20,10))
OR
fig, ax = plt.subplots(figsize=(20, 10))

adding secondry y-axis in python line plot [duplicate]

This question already has answers here:
secondary_y=True changes x axis in pandas
(2 answers)
Plot multiple Y axes
(3 answers)
Closed 4 years ago.
I want to add secondary y-axis. I have my data in CSV with three column date, lscc and cc. I want to add LSCC as first y-axis and CC as secondry. so far I have done this
df=pd.read_csv("E29Lsccvalue.csv", index_col='Date' )
plt.ylabel("")
plt.xlabel("Low level Similarity Class Cohesion (LSCC) Evolution")
df.plot(kind="line", marker='o',legend=None)
plt.xticks(rotation=90)
plt.show()
thanks
Within matplotlib I have used twinx() when I want to utilize the existing X-axis I have created, yet plot more data on top with a different Y axis. In your case with df as the first plot object:
axCC = df.twinx() # second axis sharing the same X axis of the original
Then you can include plots, labels, and other parameters referenced to this axis through calls such as:
axCC.set_ylabel("ExampleLabel",color="tab:red")
axCC.plot(xData,yData,color="blue")
Etc, etc.
A fully functional example with more detail is shown here
Although no reproducible date is provided, I guess you can achieve the desired result by doing this:
ax = df.plot(secondary_y='CC')
eventually adding all your ax customization required
edit: dotted line customization
Suppose you need a dotted vertical line at a certain position on your x-axis (in this example, at position 2 from your pandas index), use axvline and ':' as linestyle (dots)
ax = a.plot(secondary_y='Price')
ax.axvline(a.index.values[2], linestyle=':')

Categories