how to attach a color gradient to every bar using matplotlib [duplicate] - matplotlib

This question already has an answer here:
how to plot gradient fill on the 3d bars in matplotlib
(1 answer)
Closed 5 years ago.
The standard way in which I create bar plots in matplotlib is using ax.bar3d. This has the disadvantage of returning block of solid color. Does anyone know how to attach a gradient color to every bar? I am think in reproducing Fig. 1 from https://arxiv.org/pdf/1706.09289.pdf.

Try this:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(18,12))
ax = fig.add_subplot(111, projection='3d')
x_data, y_data = np.meshgrid(np.arange(5),np.arange(3))
z_data = np.random.rand(3,5)
colors = ['r','g','b'] # colors for every line of y
# plot colored 3d bars
for i in xrange(3): # cycle though y
# I multiply one color by len of x (it is 5) to set one color for y line
ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=colors[i]*5)
# or use random colors
# ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=[np.random.rand(3,1),]*5)
plt.show()
Result:

Related

Data visualization using Matplotlib

By using this code I'm able to generate 20 data points on y-axis corresponding to x-axis, but I want to mark the 25 data points on the line as downward pointed triangles without changing arr_x=np.linspace(0.0,5.0,20) to arr_x=np.linspace(0.0,5.0,25).
will it possible to mark additional data points on y-axis without changing x-axis ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def multi_curve_plot():
# Write your functionality below
fig=plt.figure(figsize=(13,4))
ax=fig.add_subplot(111)
arr_x=np.linspace(0.0,5.0,20)
arr_y1=np.array(arr_x)
arr_y2=np.array(arr_x**2)
arr_y3=np.array(arr_x**3)
ax.set(title="Linear, Quadratic, & Cubic Equations", xlabel="arr_X",
ylabel="f(arr_X)")
ax.plot(arr_x, arr_y1, label="y = arr_x", color="green", marker="v")
ax.plot(arr_x, arr_y2, label ="y = arr_x**2", color ="blue", marker="s")
ax.plot(arr_x, arr_y3, label="y = arr_x**3", color="red", marker="o")
plt.legend()
return fig
return None
multi_curve_plot()
I tried changing arr_x=np.linspace(0.0,5.0,20) to arr_x=np.linspace(0.0,5.0,25). But I want to show 25 data points on y axis without changing x-axis attributes.

Warping Matplotlib/Seaborn Scatter Plot into Parallelogram

I have a 2D scatterplot (in either matplotlib or seaborn) and an angle e.g. 64 degrees. I want to plot a warped version of this scatter plot where the x-axis of the first plot is held fixed but the second axis is warped such that the y-axis of the first plot is now at the given angle with the x-axis of the new plot (i.e. 64 degrees). How can I do this?
In other words, I want to take the original scatter plot and "push" the y-axis to the right to form a parallelogram-like plot where the angle between the old y axis and the old/new x-axis is the given angle.
Here is an adaption of an old tutorial example:
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
import numpy as np
fig = plt.figure()
skewed_transform = Affine2D().skew_deg(90 - 64, 0)
grid_helper = floating_axes.GridHelperCurveLinear(skewed_transform, extremes=(-0.5, 1.5, -0.5, 1.5))
skewed_ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
skewed_ax.set_facecolor('0.95') # light grey background
skewed_ax.axis["top"].set_visible(False)
skewed_ax.axis["right"].set_visible(False)
fig.add_subplot(skewed_ax)
x, y = np.random.rand(2, 100) # random point in a square of [0,1]x[0,1]
skewed_ax.scatter(x, y, transform=skewed_transform + skewed_ax.transData)
plt.show()

Plotting fuzzy data with matplotlib

I don't know where to start, as I think it is a new approach for me. Using matplotlib with python, I would like to plot a set of fuzzy numbers (for instance a set of triangular or bell curve fuzzy numbers) as in the picture below:
You can plot the curves recurrently. My try at reproducing your example (including the superposition of labels 1 and 6):
import matplotlib.pyplot as plt
import numpy as np
# creating the figure and axis
fig, ax = plt.subplots(1,1,constrained_layout=True)
# generic gaussian
y = np.linspace(-1,1,100)
x = np.exp(-5*y**2)
center_x = (0,2,4,1,3,0,5)
center_y = (6,2,3,4,5,6,7)
# loop for all the values
for i in range(len(center_x)):
x_c, y_c = center_x[i], center_y[i]
# plotting the several bells, relocated to (x_c, y_c)
ax.plot(x + x_c,y + y_c,
color='red',linewidth=2.0)
ax.plot(x_c,y_c,
'o',color='blue',markersize=3)
# adding label
ax.annotate(
str(i+1),
(x_c - 0.1,y_c), # slight shift in x
horizontalalignment='right',
verticalalignment='center',
color='blue',
)
ax.grid()
Every call to ax.plot() is adding points or curves (to be more precise, Artists) to the same axis. The same for ax.annotate() to create the labels.

Change histogram bars color [duplicate]

This question already has answers here:
Matplotlib histogram with multiple legend entries
(2 answers)
Closed 4 years ago.
I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code).
I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(1000)
plt.hist(data,color = 'r')
One way may be similar to approach in other answer:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
data = np.random.rand(1000)
N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)
for i in range(0,3):
patches[i].set_facecolor('b')
for i in range(3,5):
patches[i].set_facecolor('r')
for i in range(5, len(patches)):
patches[i].set_facecolor('black')
plt.show()
Result:

Change colour of curve according to its y-value in matplotlib [duplicate]

This question already has answers here:
Having line color vary with data index for line graph in matplotlib?
(4 answers)
Set line colors according to colormap
(1 answer)
Closed 8 years ago.
I'm trying to replicate the style of the attached figure using matplotlib's facilities.
Basically, I want to change the colour of the curve according to its y-value using matplotlib.
The plot you've shown doesn't have the color set by the vertical axis of the plot (which is what I would consider the y-value). Instead, it just has 8 different plots overlain, each with a different color, without stating what the color means.
Here's an example of something that looks like your plot:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# some fake data:
x = np.linspace(0, 2*np.pi, 1000)
fs = np.arange(1, 5.)
ys = np.sin(x*fs[:, None])
for y, f in zip(ys, fs):
plt.plot(x, y, lw=3, c=cm.hot(f/5))
If you actually want the color of one line to change with respect to its value, you have to kind of hack it, because any given Line2D object can only have one color, as far as I know. One way to do this is to make a scatter plot, where each dot can have any color.
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(2*x)
plt.scatter(x,y, c=cm.hot(np.abs(y)), edgecolor='none')
Notes:
The color vector should range between 0 and 1, so if y.max() > 1, then normalize by it: c=cm.hot(y/y.max()) and make sure it's all positive.
I used edgecolor='none' because by default the scatter markers have a black outline which makes the it look less like a uniform line.
If your data is spaced too far, you'll have to interpolate the data if you don't want gaps between markers.