2016-04-14 27 views
2

我創造了我的應用程序柱形圖看起來是這樣的:製作圖表圖例代表兩種顏色

Column chart with positive and negative colors

正如你可以看到正值青蔥,負值爲紅色。我需要在傳奇中表現這一點。我只是不知道如何。

我已經嘗試過:

我加CustomItemsLegend。下面是代碼:

Legend currentLegend = chart.Legends.FindByName(chart.Series[series].Legend); 
if (currentLegend != null) 
{ 
    currentLegend.LegendStyle = LegendStyle.Table; 
    LegendItem li    = new LegendItem(); 
    li.Name      = series; 
    li.Color     = Color.Red; 
    li.BorderColor    = Color.Transparent; 
    currentLegend.CustomItems.Add(li); 
} 

這導致以下表示:

Column chart with legend representing positive and negative color

我可以忍受的。但只要我在圖表中添加更多系列,元素的順序就會被破壞。這裏有一個例子:

enter image description here

我想有兩個選項之一:

  1. 保持積極和消極的色彩一起
  2. 或一個更好的解決方案可能是有隻是傳說中的一塊瓷磚是雙色的。事情是這樣的:

enter image description here

能否請你幫我解決這個問題?

非常感謝提前!

回答

2

是的,你可以做到這一點。但請注意,您無法真正修改原始Legend。因此,爲獲得完美結果,您需要創建一個新的自定義Legend

請參閱here for an example那樣做;注意特別的定位..!

但也許你可以輕鬆一點;見下文!

要理解的第一條規則是,添加LegendItems總是去末尾的名單。所以你不能把它們放在一起,除非你增加Series開始。你可以做到這一點,通過使用Series.Insert(..),但使用那些雙色矩形更好,imo ..

要顯示出你想要的圖形,只需創建爲位圖,可以用在磁盤上飛,並將其存儲在Images收集圖表中:

Legend L = chart1.Legends[0]; 
Series S = chart1.Series[0]; 

// either load an image from disk (or resources) 
Image img = Image.FromFile(someImage); 

// or create it on the fly: 
Bitmap bmp = new Bitmap(32, 14); 
using (Graphics G = Graphics.FromImage(bmp)) 
{ 
    G.Clear(Color.Red); 
    G.FillPolygon(Brushes.LimeGreen, new Point[] { new Point(0,0), 
     new Point(32,0), new Point(0,14)}); 
} 

現在把它添加到圖表的NamedImage集合:

chart1.Images.Add(new NamedImage("dia", bmp)); 

現在,您可以根據需要創建儘可能多的LegendItems

LegendItem newItem = new LegendItem(); 
newItem.ImageStyle = LegendImageStyle.Rectangle; 
newItem.Cells.Add(LegendCellType.Image, "dia", ContentAlignment.MiddleLeft); 
newItem.Cells.Add(LegendCellType.Text, S.Name, ContentAlignment.MiddleLeft); 

,並將它們添加到Legend

L.CustomItems.Add(newItem); 

可惜你不能刪除原始項目。

你能做什麼,除了從頭創建一個新的Legend,是這樣的:

清除文字是這樣的:

S.LegendText = " "; // blank, not empty! 

正如你所設置的所有DataPointsColors反正,你也可以擺脫藍色矩形:

S.Color = Color.Transparent; 

這會也使所有點沒有顏色透明,所以一定要給他們上色!

注意的是,在聯想一些空間它仍然採取!

下面是結果,用一些帶顏色的點,你行系列補充說:

enter image description here

+0

非常感謝,這有助於! – Konstantin