如何使用matplotlib绘制2D渐变(彩虹)?

时间:2017-05-06 17:57:28

标签: python matplotlib

我尝试使用matplotlib库绘制梁的应力。

我通过使用公式计算并将其绘制为示例:

Figure 1: Example of before and after of finite element of beam

如图1所示,您将看到绿色光束在元素3和元素8处具有更大的应力因此,如果我通过彩虹渐变填充颜色,则所有蓝色光束将是相同的颜色但是绿色光束将具有元素3和8的不同颜色将比其他颜色更多。

example of stress plot

以下是我的一些代码。 将matplotlib.pyplot导入为plt     将matplotlib导入为mpl

node_coordinate = {1: [0.0, 1.0], 2: [0.0, 0.0], 3: [4.018905, 0.87781], 4: [3.978008, -0.1229], 5: [1.983549, -0.038322], 6: [2.013683, 0.958586], 7: [3.018193, 0.922264],
                   8: [2.979695, -0.079299], 9: [1.0070439, 0.989987], 10: [0.9909098, -0.014787999999999999]}
element_stress = {'1': 0.2572e+01, '2': 0.8214e+00, '3': 0.5689e+01, '4': -0.8214e+00, '5': -0.2572e+01, '6': -0.4292e+01, '7': 0.4292e+01, '8': -0.5689e+01}

cmap = mpl.cm.jet

fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.4, 0.9, 0.15])
# ax1 = fig.add_axes([0.2572e+01, 0.8214e+00, 0.5689e+01, -0.8214e+00, -0.2572e+01, -0.4292e+01, 0.4292e+01, -0.5689e+01])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, orientation='vertical')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, orientation='horizontal')
plt.show()

您将看到我知道所有节点坐标以及元素的压力值。

P.S。对不起我的语法,我不是本地人。

谢谢。建议。

1 个答案:

答案 0 :(得分:3)

example之后,我认为这就是你要找的东西:

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np

node_coordinate = {1: [0.0, 1.0], 2: [0.0, 0.0], 3: [4.018905, 0.87781],
                   4: [3.978008, -0.1229], 5: [1.983549, -0.038322],
                   6: [2.013683, 0.958586], 7: [3.018193, 0.922264],
                   8: [2.979695, -0.079299], 9: [1.0070439, 0.989987],
                   10: [0.9909098, -0.014787999999999999]}
element_stress = {1: 0.2572e+01, 2: 0.8214e+00, 3: 0.5689e+01,
                  4: -0.8214e+00, 5: -0.2572e+01, 6: -0.4292e+01,
                  7: 0.4292e+01, 8: -0.5689e+01}

n = len(element_stress.keys())
x = np.empty(n)
y = np.empty(n)
d = np.empty(n)

for i in element_stress.keys():
    x[i-1] = node_coordinate[i][0]
    y[i-1] = node_coordinate[i][1]
    d[i-1] = element_stress[i]

triang = tri.Triangulation(x, y)

cmap = mpl.cm.jet
fig = plt.figure(figsize=(8, 4))

ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax1.tricontourf(triang, d, cmap=cmap)

ax2 = fig.add_axes([0.05, 0.4, 0.9, 0.15])
x_2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
d_2 = x_2[:]
triang_2 = tri.Triangulation(x_2, y_2)
ax2.tricontourf(triang_2, d_2, cmap=cmap)

fig.show()

enter image description here

第二个例子是为了澄清而添加的,因为从给定数据中获得的图表与您从Comsol获得的图表不同。

相关问题