2015-09-06 68 views
-2

我正在使用System.Windows.Forms.DataVisualization.Charting。 現在我有一個這樣的柱形圖。圖表列網格

Image

但我需要的電網在一邊,這樣的列。

Image

我該怎麼辦呢?


我的數據來自DataGridView,所以我的代碼看起來像這樣。

var ser = chart1.Series.Add("ana"); 
ser.IsValueShownAsLabel = true; 
ser.IsVisibleInLegend = false; 
ser.ChartType = SeriesChartType.Column; 

//X value is string 
ser.XValueMember = dataGridView1.Columns[0].DataPropertyName; 

//Y value is int 
ser.YValueMembers = dataGridView1.Columns[1].DataPropertyName; 

chart1.DataSource = dataGridView1.DataSource; 

而且數據的DataGridView很簡單。

 
------------- 
|Month|Sales| 
------------- 
| Jan | 17 | 
------------- 
| Feb | 28 | 
------------- 
| Mar | 19 | 
------------- 
+0

更具體 – Arash

+0

投入一些精力,如果面對任何問題,然後張貼在這裏。 –

+0

您應該向我們展示如何添加'DataPoints'!他們的「X值」和「X值類型」是什麼? – TaW

回答

2

GridLinesDataPointsLabelsGridLines,但..

您可以設置IntervalMinimumX-Axis分開來調整它們:

enter image description here

但有一些額外的需要注意的..

// get a reference 
ChartArea chartArea1 = chart1.ChartAreas[0]; 

// don't start at 0 
chartArea1.AxisX.IsStartedFromZero = false; 

// pick your interval 
double interval = 1D; 
chartArea1.AxisX.MajorTickMark.Interval = interval; 

// set minimum at the middle 
chartArea1.AxisX.Minimum = interval/2d; 

// pick a column width (optional) 
chart1.Series[0].SetCustomProperty("PixelPointWidth", "30"); 

// we want the labels to sit with the points, not the grid lines.. 
// so we add custom labels for each point ranging between the grid lines.. 
for (int i = 0; i < chart1.Series[0].Points.Count; i++) 
{ 
    DataPoint dp = chart1.Series[0].Points[i]; 
    chartArea1.AxisX.CustomLabels.Add((0.5d + i) * interval, 
             (1.5d + i) * interval, dp.XValue.ToString()); 
} 

更新:

隨着更新的問題表明,你正在使用的數據綁定使用字符串作爲X值。這非常方便,但違背了Chart控件的核心本質。它的所有符號,無論是X-Value還是任何Y-Values都在內部存儲爲雙打。

隨機字符串不轉換爲加倍而你可以方便地與字符串添加DataPointsX-Values,醜陋的問題各種各樣拿出一個結果。

首先看看X-Values自己:正如我所說的,他們是雙重的;當你檢查它們的值時,你會看到它們全都是0.字符串值在哪裏?它們被放置在標籤中。

有一個問題經常發現,您現在無法訪問X-Valuesvalue expressions

另一個問題是,我們現在不能給範圍x-Values自定義標籤。

解決方案:如果我們需要自定義標籤,我們必須更改數據!

數據綁定是好的,只要確保爲您的數據源添加一個數字列包含一個月份號碼並將其設置爲該系列的XValueMember

您可以使該列在您的DataGridView中不可見。

最後,您會希望像以前一樣創建自定義標籤;只需將其內容更改爲從包含月份名稱的字符串列中拉出即可。

下面是它看起來像在這裏:

enter image description here

+0

我的不好。我更詳細地更新了我的問題。我正在使用dataGridView的數據,間隔技巧似乎不起作用。 –

+0

我明白了。那麼您目前沒有__real__ X值。您正在使用的字符串僅用於軸標籤;如果你看看創建的DataPoints的X值,你會發現__they都是0__,所以這個技巧是行不通的。我明天更新答案.. – TaW

+0

謝謝。我知道有解決方法是用AddPoint和CustomLabels.Add手動添加這些數據,但我正在尋找更好的方法來做到這一點(如果有的話)。 –