# how to color unstructured grid (.vtu) ?

**URL:** https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140
**Category:** VR/AR
**Tags:** vtk
**Created:** [August 14, 2022, 4:55pm UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140 "2022-08-14T16:55:48Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![graysuit](https://discourse.paraview.org/user_avatar/discourse.paraview.org/graysuit/32/9742_2.png) [@graysuit](https://discourse.paraview.org/u/graysuit)
#### Post date: [August 14, 2022, 4:55pm UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/1 "2022-08-14T16:55:48Z")

</div>

My whole source code is present [here](https://github.com/learning-hide/vtktest) including [block.vtu](https://github.com/learning-hide/vtktest/tree/main/vtktest/vtktest/bin/x86/Debug) file for testing purpose. I will discuss important functions here.

This code can color \*.vtp, \*.vtk. But same code fails to color \*.vtu.

I have list of vtkactors. And I specify which actor to set properties from.

1. This code which gets all column names from an actor:

```auto
public static List<string> getColumns(int actorIndex)
{
    List<string> colums = new List<string>();
    vtkActor actor = actors[actorIndex];
    var output = actor.GetMapper().GetInputAsDataSet();
    var cell = output.GetCellData();
    for (int i = 0; i < cell.GetNumberOfArrays(); i++)
    {
        var colm = cell.GetArrayName(i);
        if (colm != null) colums.Add(colm);
    }
    return colums; //['CU_OK','D1','Domain','IJK','IX','IY'...]
}

```

1. This code colors the model of specific column:

```auto
public static void setColors(int actorIndex, string column)
{
    List<string> colums = new List<string>();
    vtkActor actor = actors[actorIndex];
    var output = actor.GetMapper().GetInputAsDataSet();
    var colors = vtkUnsignedCharArray.New();
    colors.SetNumberOfComponents(3);
    colors.SetName("Colors");

    var cell = output.GetCellData();
    for (int i = 0; i < cell.GetNumberOfArrays(); i++)
    {
        var cells = cell.GetArray(i);
        if (cells == null) continue;
        if (column != cell.GetArrayName(i)) continue;
        for (int j = 0; j < cells.GetNumberOfTuples(); j++)
        {
            var c = color_range((cells.GetComponent(i, j) / cell.GetArray(i).GetRange()[1]) * 100);
            var R = c.R;
            var G = c.G;
            var B = c.B;
            colors.InsertNextTuple3((double)R, (double)G, (double)B);
            colors.InsertNextTuple3((double)R, (double)G, (double)B); //even tried with and without inserting second tuple
        }

    }
    output.GetPointData().SetScalars(colors); //even tried with GetCellData(), but no luck
}

```

1. This code gets range(min,max) of values from specific column:

```auto
public static double[] getRange(int actorIndex, string column)
{
    List<string> colums = new List<string>();
    vtkActor actor = actors[actorIndex];
    var output = actor.GetMapper().GetInputAsDataSet();
    var cell = output.GetCellData();
    for (int i = 0; i < cell.GetNumberOfArrays(); i++)
    {
        var colm = cell.GetArrayName(i);
        var arr = cell.GetArray(i);
        if (column == colm)
        {
            if (arr == null) return null;
            return arr.GetRange(); // new double[] { min, max }
        }
    }
    return null;
}

```

### ACTUAL OUTPUT for VTP and VTK (GOOD):

The result is fine. This is how drillholes are shown in by my code. [![colored drillhole](https://discourse.paraview.org/uploads/default/original/2X/c/cb2bad5a0e640cf44cf468d1216ecff8d4d22e01.png)](https://i.stack.imgur.com/Gz0WL.png)

### EXPECTED OUTPUT for VTU (GOOD):

See how its colored. This is what PARAVIEW software can show: [![Paraview Block Model](https://discourse.paraview.org/uploads/default/original/2X/b/b634086049d9d9a2827a62416eedee95127ec5f8.png)](https://i.stack.imgur.com/6KxaP.png)

### ACTUAL OUTPUT for VTU (BAD):

This is how my code show that model: [![My Block Model](https://discourse.paraview.org/uploads/default/original/2X/c/ce72be9f29bcf9ccd36c2651c3838b354e1d883b.png)](https://i.stack.imgur.com/6EWU0.png)

I also tried:

I tried following question, but vtu color has no effect. I tried cell data too instead of point data. I also tried lookup table, it do shows with color scalebar but has no effect on model color.

The strange things are that:

- all vtp files work (to color)and all vtu files fails

- vtu file show colorful fine on paraview, but not in my code

---

<div class="post-metadata">

### Author: ![Kenichiro-Yoshimi](https://discourse.paraview.org/letter_avatar_proxy/v4/letter/k/ecc23a/32.png) [@Kenichiro-Yoshimi](https://discourse.paraview.org/u/Kenichiro-Yoshimi)
#### Post date: [August 15, 2022, 8:38am UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/2 "2022-08-15T08:38:38Z")

</div>

Hello,

I am not sure if this is a proper solution, but it might work if you create a new mapper at the end of the `setColors` function.

```auto
            output.GetPointData().SetScalars(colors);

+ vtkDataSetMapper mapper = vtkDataSetMapper.New();
+ mapper.SetInput(output);
+ actor.SetMapper(mapper);
        }

```

It may also be possible to draw the array directly instead of creating an RGB array. (The following was also added at the end of the `setColors` function.)

```auto
            #output.GetPointData().SetScalars(colors);

+ var mapper = actor.GetMapper();
+ mapper.SelectColorArray(column);
+ mapper.SetScalarModeToUsePointFieldData();
+ var range1 = getRange(actorIndex, column);
+ mapper.SetScalarRange(range1[0], range1[1]);
        }

```

I think your question will be better answered in the vtk forum ([https://discourse.vtk.org/](https://discourse.vtk.org/)) than in the ParaView forum.

---

<div class="post-metadata">

### Author: ![graysuit](https://discourse.paraview.org/user_avatar/discourse.paraview.org/graysuit/32/9742_2.png) [@graysuit](https://discourse.paraview.org/u/graysuit)
#### Post date: [August 15, 2022, 1:39pm UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/3 "2022-08-15T13:39:37Z")

</div>

Wow. I been asking same question on sereval forums, even on discourse vtk. Its been 2-3 month. But only you got real solution.  
Didn’t expected, solution would that simple.

Your first code works. Here’s output I got:

 ![Capture](https://discourse.paraview.org/uploads/default/original/2X/5/51dd5ccdb5f450ed4578af938a0f645c8b22f6b3.png)

However, I’m seeing an warning in vtk unmanaged libraries:

```auto
Warning: In ..\..\..\..\vtksource-prefix\src\vtksource\Filtering\vtkDataSet.cxx, line 413
vtkUnstructuredGrid (0F089B08): Point array Colors with 3 components, has 257902 tuples but there are only 256756 points

```

So from last line, I think problem is, my color array has 257902 values whereas total points inside model was 256756.

I investigated and noted several meaningful integers:

```auto
output.GetMaximumNumberOfPieces(); // 1
output.GetNumberOfCells(); // 231659
output.GetNumberOfPoints(); // 256756 IMPORTANT

cell.GetNumberOfArrays(); // 10
cell.GetNumberOfTuples(); // 231659
cell.GetNumberOfComponents(); // 10

cells.GetNumberOfComponents(); // 1
cells.GetNumberOfTuples(); // 231659
cells.GetNumberOfComponentsMaxValue(); // 2147483647
cells.GetNumberOfComponentsMinValue(); // 0

```

So I replaced this code:

```auto
colors.InsertNextTuple3((double)R, (double)G, (double)B);
colors.InsertNextTuple3((double)R, (double)G, (double)B);

```

with

```auto
if (colors.GetNumberOfTuples() >= output.GetNumberOfPoints())
{
    break;
}
else colors.InsertNextTuple3((double)R, (double)G, (double)B);
if (colors.GetNumberOfTuples() >= output.GetNumberOfPoints())
{
    break;
}
else colors.InsertNextTuple3((double)R, (double)G, (double)B);

```

It do colors as well and also warning doesn’t appears.  
But another error appears. I can’t able to copy whole error, as it remain freezed.

 ![error](https://discourse.paraview.org/uploads/default/original/2X/7/7f138a67d2cf394413fa9d903228d925a04a97ad.png)

I believe there’s tiny mistake I may be doing.

For second code, unfortunately has no effect.

---

<div class="post-metadata">

### Author: ![graysuit](https://discourse.paraview.org/user_avatar/discourse.paraview.org/graysuit/32/9742_2.png) [@graysuit](https://discourse.paraview.org/u/graysuit)
#### Post date: [August 15, 2022, 2:12pm UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/4 "2022-08-15T14:12:31Z")

</div>

So I catch that error using

```auto
vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
renderWindow.ErrorEvt += vtk_error;

void vtk_error(vtkObject sender, vtkObjectEventArgs e)
{
    string s = "unknown";
    if (e.CallData != IntPtr.Zero)
    {
        s = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(e.CallData);
    }

    Console.Write(string.Format("Error: sender='{0}' e='{1}' s='{2}'", sender, e, s));
}

```

Here’s full error log:

```auto
Error: sender='vtkWin32OpenGLRenderWindow (0C63D900)
  Debug: Off
  Modified Time: 6522
  Reference Count: 2
  Registered Events:
    Registered Observers:
      vtkObserver (0C6516F0)
        Event: 40
        EventName: WarningEvent
        Command: 0C651A50
        Priority: 0
        Tag: 2
      vtkObserver (0C63BE50)
        Event: 39
        EventName: ErrorEvent
        Command: 0C642FF8
        Priority: 0
        Tag: 1
  Erase: On
  Window Name: Visualization Toolkit - Win32OpenGL #1
  Position: (0, 0)
  Size: (595, 421)
  Mapped: 1
  OffScreenRendering: 0
  Double Buffered: 1
  DPI: 96
  TileScale: (1, 1)
  TileViewport: (0, 0, 1, 1)
  Borders: On
  IsPicking: Off
  Double Buffer: On
  Full Screen: Off
  Renderers:
    Debug: Off
    Modified Time: 1002
    Reference Count: 1
    Registered Events: (none)
    Number Of Items: 1
  Stereo Capable Window Requested: No
  Stereo Render: Off
  Point Smoothing: Off
  Line Smoothing: Off
  Polygon Smoothing: Off
  Anti Aliased Frames: 0
  Abort Render: 0
  Current Cursor: 0
  Desired Update Rate: 0.0001
  Focal Depth Frames: 0
  In Abort Check: 0
  NeverRendered: 0
  Interactor: 0C63E368
  Motion Blur Frames: 0
  Swap Buffers: On
  Stereo Type: CrystalEyes
  Number of Layers: 1
  AccumulationBuffer Size 0
  AlphaBitPlanes: Off
  AnaglyphColorSaturation: 0.65
  AnaglyphColorMask: 4 , 3
  PainterDeviceAdapter:
    Debug: Off
    Modified Time: 32
    Reference Count: 1
    Registered Events: (none)
  MultiSamples: 8
  StencilCapable: False
  ReportGraphicErrors: Off
  ContextId: 00010000
  Next Window Id: 00000000
  Window Id: 000B020A

' e='Kitware.VTK.vtkObjectEventArgs' s='ERROR: In ..\..\..\..\vtksource-prefix\src\vtksource\Rendering\vtkWin32OpenGLRenderWindow.cxx, line 247
vtkWin32OpenGLRenderWindow (0C63D900): wglMakeCurrent failed in MakeCurrent(), error: The requested resource is in use.

'

```

---

<div class="post-metadata">

### Author: ![graysuit](https://discourse.paraview.org/user_avatar/discourse.paraview.org/graysuit/32/9742_2.png) [@graysuit](https://discourse.paraview.org/u/graysuit)
#### Post date: [August 16, 2022, 6:49am UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/5 "2022-08-16T06:49:15Z")

</div>

I want to accept your answer as solution. But not sure how I can do it, because there’s no solution button visible.

 ![image](https://discourse.paraview.org/uploads/default/original/2X/3/39ec5509321af497ac0e770e030bf6ff0803d586.png)

Also previously, I bountied on stack overflow. So go, also write your answer there as well and get bounty.

> <https://stackoverflow.com/questions/73247453/how-to-color-unstructured-grid-vtu-in-vtk>

Although bounty is small worth 50 only, but at least it meant to show achievement that rarely anyone can get.

---

<div class="post-metadata">

### Author: ![Kenichiro-Yoshimi](https://discourse.paraview.org/letter_avatar_proxy/v4/letter/k/ecc23a/32.png) [@Kenichiro-Yoshimi](https://discourse.paraview.org/u/Kenichiro-Yoshimi)
#### Post date: [August 16, 2022, 7:53am UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/6 "2022-08-16T07:53:40Z")

</div>

Thank you, I wrote the same answer as here on stack overflow.

---

<div class="post-metadata">

### Author: ![cory.quammen](https://discourse.paraview.org/user_avatar/discourse.paraview.org/cory.quammen/32/11193_2.png) [@cory.quammen](https://discourse.paraview.org/u/cory.quammen)
#### Post date: [August 16, 2022, 9:16pm UTC](https://discourse.paraview.org/t/how-to-color-unstructured-grid-vtu/10140/7 "2022-08-16T21:16:57Z")

</div>

> [@graysuit](#):
>
> But not sure how I can do it, because there’s no solution button visible.

Thanks for pointing this out. It should be fixed now.
