在不同对象上的多个位置实例的图形X Y位置

时间:2018-09-12 10:54:25

标签: python python-3.x pandas matplotlib

我正在尝试以如下所示的格式生成XY散点图:

Example XY Scatter Plot

我的数据框(df)如下:

enter image description here

如果轮播编号为1、2、3或4,则圆圈应为一种颜色,如果大于或等于5,则圆圈应为不同的颜色。

上面的XY散点图中所示的圆以标称的X Y坐标为中心,其半径等于TOLPL。

到目前为止,我有一些(狡猾的)代码可以成功生成大量图形,但是它仅显示一个X Y点(循环中的最后一个),而不是全部。

理想情况下,对于描述中的每个项目,图形将显示为5幅,然后向下显示以形成网格。

代码是:


编辑2018年9月12日15:57

  • 添加代码以使用我的数据生成示例DataFrame。
  • 清理代码,使其成为到目前为止我所掌握的最小的工作示例。

df = {'DESCRIPTION': ['Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'Hub Bore Top', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1', 'View Y Top Hole 1'],
'CAROUSEL': [1, 1, 1, 6, 6, 2, 2, 2, 6, 6, 6, 2, 2, 2, 6, 1, 1, 1, 1, 2, 6],
'AXIS': ['Y', 'Z', 'D', 'D', 'Z', 'Y', 'Z', 'D', 'Y', 'Y', 'X', 'D', 'X', 'Y', 'Z', 'D', 'Z', 'Y', 'X', 'Z', 'D'],
'NOMINAL': [0.000, 3.000, 85.000, 85.000, 3.000, 0.000, 3.000, 85.000, 0.000, -7.087, 94.234, 10.600, 94.234, -7.087, 11.000, 10.600, 11.000, -7.087, 94.234, 11.000, 10.600],
'MEAS': [0.081, 3.047, 85.013, 85.013, 3.001, 0.077, 2.992, 85.001, -0.038, -7.075, 94.478, 10.456, 94.479, -7.160, 11.000, 10.466, 11.000, -7.166, 94.487, 11.000, 10.405],
'TOLPL': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.25, 0.25, 0.1, 0.25, 0.25, 0.1, 0.1, 0.1, 0.25, 0.25, 0.1, 0.1],
'TOLMI': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.25, 0.25, 0.1, 0.25, 0.25, 0.1, 0.1, 0.1, 0.25, 0.25, 0.1, 0.1]
        }

feat = df

features = set(feat['DESCRIPTION'].tolist())
carousels = set(feat['CAROUSEL'].tolist())

for feat_idx, feature in enumerate(features): 
    feat = df

    for caro_idx, carousel in enumerate(carousels):
            # select all data for current carousel and store in feat
            feat = feat[feat['CAROUSEL']==carousel]

            feat = feat.pivot(index='DESCRIPTION', columns='AXIS', values=['MEAS', 'NOMINAL', 'TOLPL', 'TOLMI'])

            if caro_idx == 0:
                try:
                    # store data from current feature and carousel in variables
                    nominal_x = feat['NOMINAL'][['X']]['X'][feat_idx]
                    nominal_y = feat['NOMINAL'][['Y']]['Y'][feat_idx]
                    tol_rad = feat['TOLPL'][['X']]['X'][feat_idx]
                    description = feat.index[feat_idx]

                    # generate matplotlib graph with tolerance circle
                    fig, ax = plt.subplots(figsize=(2,2))
                    tol_circle = plt.Circle((nominal_x, nominal_y), tol_rad, color='grey', fill=False)
                    ax.set_xlim((nominal_x - 4*tol_rad, nominal_x + 4*tol_rad))
                    ax.set_ylim((nominal_y - 4*tol_rad, nominal_y + 4*tol_rad))
                    ax.add_artist(tol_circle)
                    ax.set(title=description, xlabel='x (mm)', ylabel='y (mm)')
                    colour='r'
                except:
                    pass
            # change plotted point colour if carousel number is 5 or greater
            elif caro_idx <4:
                colour = 'r'
            else:
                colour= 'b'

            # get the measured x, y, and d values
            meas_x = feat['MEAS'][['X']]['X'][feat_idx]
            meas_y = feat['MEAS'][['Y']]['Y'][feat_idx]
            meas_d = feat['MEAS'][['D']]['D'][feat_idx]

            # create a matplotlib circle with the measured x, y, and d values and plot them on current ax. 
            plot_circle = plt.Circle((meas_x, meas_y), tol_rad/4, color=colour)
            ax.add_artist(plot_circle)

因此,作为概述,代码创建了描述列中所有唯一“功能”以及唯一轮播编号的列表。

然后,我将数据旋转到特定的轮播编号,获取每个要素的值,然后进行绘制。我不知道如何正确地做到这一点,这就是为什么它如此笨拙!

过去几天我一直在为此苦苦挣扎,非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

让我们为此努力吧

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(16, 10))


for k in range(1,5):

    ax = fig.add_subplot(2,2,k)

    ax.set_xlim((-2.0, 2.0))
    ax.set_ylim((-2.0, 2.0))

    x, y, z = np.random.rand(3)

    tol_circle = plt.Circle((x, y), np.random.rand(), color='grey', fill=False)

    ax.add_artist(tol_circle)

    ax.scatter(x, y)

    x, y, z = np.random.rand(3)

    plot_circle = plt.Circle((x, y), z, color='red', fill=False)
    ax.add_artist(plot_circle)

    ax.scatter(x, y)

plt.show()

现在,您要做什么?

enter image description here

答案 1 :(得分:0)

将其张贴在此处,以防将来有人需要做相同类型的事情。

我设法使用matplotlib列构面获取了要查找的图形。请参见下面的功能。

def x_y_pos_facet(dataframe):
    m = dataframe

    # Only select X and Y values
    m = m[((m['AXIS'] == 'X') | (m['AXIS'] == 'Y'))]

    # Move X and Y values into their own columns, and group by description and carousel.
    m = m.pivot_table(
        index=['DESCRIPTION', 'CAROUSEL'], columns=['AXIS'], values=['OFFSET'])

    # Move the DESCRIPTION CAROUSEL index into a single column. 
    n = m
    n = n.reset_index()

    # Reduce column multi index to single index
    n.columns = n.columns.map(''.join)

    #Graph styling. Also seperates the eight measured items into two groups with colours. 
    sns.set_style('whitegrid')
    colours = [
        'cobalt blue', 'cobalt blue', 'cobalt blue', 'cobalt blue',
        'bright orange', 'bright orange', 'bright orange', 'bright orange'
    ]
    colours = sns.color_palette(sns.xkcd_palette(colours))

    chart = sns.lmplot(
        x='OFFSETX',
        y='OFFSETY',
        data=n,
        hue='CAROUSEL',
        fit_reg=False,
        col='DESCRIPTION', #This is the magic! Creates a chart for each description item
        col_wrap=2, #Makes the graphs start a new row every two graphs.
        palette=colours)
chart.set(
    xlabel='X Axis Offset From Nominal (mm)',
    ylabel='Y Axis Offset From Nominal (mm)',
    xlim=(-1.6, 1.6),
    ylim=(-1.6, 1.6))