This question already has answers here:
How to shift a column in Pandas DataFrame
(9 answers)
Closed 4 years ago.
I have the following code:
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
fig, ax = plt.subplots(2,1, figsize=(10, 5))
plt.suptitle('My Data', x = 0.5, y = 1.0, fontsize = '8')
for i in range(0,2):
l1, = ax[i].plot(data_df['col_A'][101:200] , color = 'black')
l2, = ax[i].plot(data_df['col_B'][101:200], color = 'red')
plt.show()
plt.tight_layout()
And here is an output figure:
I am wondering if we could shift the entire red series to the left by 6 steps?
(I tried:
l2, = ax[i].plot(data_df_new['createvm_duration'][101-6:200-6], color = 'red')
which is not what I want because I want the x-axis ticks remain the same, but re-match of black and red peaks.)
Thanks!
Try shift the column by -6 before indexing it:
ax[i].plot(data_df['col_B'].shift(-6)[101:200], color = 'red')
Related
This question already has answers here:
How to change Border width in MatPlotLib?
(1 answer)
How to add border or frame around individual subplots
(2 answers)
matplotlib border width
(3 answers)
How to add black border to matplotlib 2.0 `ax` object In Python 3?
(3 answers)
Closed 19 days ago.
How can I make a plot surrounded with a bold line, like so?
I would use the set_linewidth and set_color parameters from matplotlib spines :
An axis spine -- the line noting the data area boundaries.
import matplotlib.pyplot as plt
C, W, L, T = "black", 4, 2, 7 # <- adjust here
#Color, Width, Length, Tickness --------------
fig, ax = plt.subplots(figsize=(W, L))
list_of_spines = ["left", "right", "top", "bottom"]
for sp in list_of_spines:
ax.spines[sp].set_linewidth(T)
ax.spines[sp].set_color(C)
ax.set_xticks([])
ax.set_yticks([])
plt.show();
Output :
You could use the following code that was the
answer on a similar question
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.rcParams["axes.edgecolor"] = "black"
plt.rcParams["axes.linewidth"] = 2.50
fig = plt.figure(figsize = (4.1, 2.2))
ax = fig.add_subplot(111)
You can set the width and colour of a border around the image like so:
from matplotlib import pyplot as plt
# some data for demonstration purposes
import numpy as np
x = np.random.randn(100)
# create figure
fig, ax = plt.subplots()
ax.plot(x)
# set the border width
fig.set_linewidth(10)
# set the border colour (to black in this case)
fig.set_edgecolor("k")
# show the figure
fig.show()
This gives:
This question already has answers here:
Adjust bar subplots colors to red (negative) and green(positive) using pandas.Dataframe.plot
(2 answers)
Bar Chart: How to choose color if value is positive vs value is negative
(4 answers)
How to plot different columns with different kind of plot (bar & line) without using matplotlib (only using pandas)
(2 answers)
Issues in displaying negative values on bar chart in Matplotlib
(1 answer)
Closed 1 year ago.
I have positive and negative values and I want to plot it as a bar chart. I want to plot the classic "green" positive colors and "red" negative values. I have this code currently:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
ax1.bar(x, y1, color='g')
plt.show()
add this line before ploting bar:
color = ['r' if y<0 else 'g' for y in y1]
finally code:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y2 = [10000,11682,20842,12879,4576,7845]
y1 = [-1456,-10120,-2118,10003,-2004,1644]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax2.plot(x, y2, color='k')
ax2.set_ylabel('Y2 data', color='k')
color = ['r' if y<0 else 'g' for y in y1]
ax1.bar(x, y1, color=color)
plt.show()
Output:
If you convert y1 array to numpy.array, you can use np.where like below (output from this code is same as output from first code):
y1 = np.array([-1456,-10120,-2118,10003,-2004,1644])
...
ax1.bar(x, y1, color=np.where(y1 < 0, 'r', 'g'))
Here you can find an example on how to do this:
import pandas as pd
import plotly.graph_objects as go
import numpy as np
# Data
df = pd.DataFrame({
'Net':[15,20,-10,-15],
'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})
df['Date'] = pd.to_datetime(df['Date'])
## here I'm adding a column with colors
df["Color"] = np.where(df["Net"]<0, 'red', 'green')
# Plot
fig = go.Figure()
fig.add_trace(
go.Bar(name='Net',
x=df['Date'],
y=df['Net'],
marker_color=df['Color']))
fig.update_layout(barmode='stack')
fig.show()
This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 4 years ago.
May I ask how do i adjust the size of the graph? This is my code.
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(mean, median, marker="s", linestyle="")
for i, txt in enumerate(words):
ax.annotate(txt, (mean[i],median[i]))
ax.set_xlabel("median")
ax.set_ylabel("mean")
plt.show()
I tried to use
fig,ax=plt.subplots(figsize=(20,10))
but failed.
You first must have code that can execute, prior to tweaking the size of a figure:
(I added dummy data, and now it works)
import matplotlib.pyplot as plt
if __name__ == '__main__':
fig = plt.figure()
ax = fig.add_subplot(111)
mean, median = [1, 2, 3], [4, 5, 6] # dummy data
ax.plot(mean, median, marker="s", linestyle="")
for i, txt in enumerate(['a', 'b', 'c']):
ax.annotate(txt, (mean[i], median[i]))
ax.set_xlabel("median")
ax.set_ylabel("mean")
fig, ax = plt.subplots(figsize=(10, 10)) # size in inches
plt.show()
you can basically do this:
from pylab import rcParams
rcParams[figure.figsize] = (5,4) # Size in inches
Then you may continue with your code :)
This question already has answers here:
Matplotlib scatter plot with legend
(6 answers)
Closed 5 years ago.
I'd like to make this kind of scatter plot where the points have colors specified by the "c" option and the legend shows the color's meanings.
The data source of mine is like following:
scatter_x = [1,2,3,4,5]
scatter_y = [5,4,3,2,1]
group = [1,3,2,1,3] # each (x,y) belongs to the group 1, 2, or 3.
I tried this:
plt.scatter(scatter_x, scatter_y, c=group, label=group)
plt.legend()
Unfortunately, I did not get the legend as expected. How to show the legend properly? I expected there are five rows and each row shows the color and group correspondences.
As in the example you mentioned, call plt.scatter for each group:
import numpy as np
from matplotlib import pyplot as plt
scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
cdict = {1: 'red', 2: 'blue', 3: 'green'}
fig, ax = plt.subplots()
for g in np.unique(group):
ix = np.where(group == g)
ax.scatter(scatter_x[ix], scatter_y[ix], c = cdict[g], label = g, s = 100)
ax.legend()
plt.show()
check this out:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
for g in np.unique(group):
i = np.where(group == g)
ax.scatter(scatter_x[i], scatter_y[i], label=g)
ax.legend()
plt.show()
This question already has an answer here:
How to redefine a color for a specific value in a matplotlib colormap
(1 answer)
Closed 8 years ago.
How can I create a matplotlib colormap that maps 0 (and only 0) to white, and any other value 0 < v <= 1 to a smooth gradient such as rainbow?
It seems neither LinearSegmentedColormap nor ListedColormap can do this.
There are a few ways of doing it. From your description of your values range, you just want to use cmap.set_under('white') and then set the vmin to 0 + eps.
For example:
import matplotlib.pyplot as plt
import numpy as np
cmap = plt.get_cmap('rainbow')
cmap.set_under('white') # Color for values less than vmin
data = np.random.random((10, 10))
data[3:5, 7:] = 0
# Very small float such that 0.0 != 0 + eps
eps = np.spacing(0.0)
fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', vmin=eps, cmap=cmap)
fig.colorbar(im, extend='min')
plt.show()
However, if 0 was in the middle of your data range, you could mask the values and set the color with cmap.set_bad (I'll use black as the color to distinguish from the default for masked portions.):
import matplotlib.pyplot as plt
import numpy as np
cmap = plt.get_cmap('rainbow')
cmap.set_bad('black')
data = np.random.normal(0, 1, (10, 10))
data[3:5, 7:] = 0
data = np.ma.masked_equal(data, 0)
fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap=cmap)
fig.colorbar(im)
plt.show()